随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

类一:

复制代码
// 抽象类
package Demo_1_23;

public abstract class Action {
    private final int EAT = 1;
    private final int SLEEP = 2;
    private final int WORK = 3;
    public Action() {
    }
    public abstract void sleep();
    public abstract void eat();
    public abstract void work();
    public void command(int command){
        switch (command){
            case EAT:{
                this.eat();
                break;
            }
            case SLEEP:{
                this.sleep();
                break;
            }
            case WORK:{
                this.work();
                break;
            }
            default:
                System.out.println("指令错误!");
        }
    }
}
复制代码

类二:

复制代码
//机器人类
package Demo_1_23;

public class Robot extends Action{
    private String name;

    public Robot() {
    }

    public Robot(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void eat() {
        System.out.println(this.name + "即将充电!");
    }

    @Override
    public void sleep() {
        System.out.println(this.name + "即将关机!");
    }

    @Override
    public void work() {
        System.out.println(this.name + "即将开始工作!");
    }

    @Override
    public void command(int code){
        super.command(code);
    }

    @Override
    public String toString() {
        return "Robot:" +
                "name='" + name + '\'' +
                ' ';
    }
}
复制代码

 

主类:

复制代码
package Demo_1_23;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //  创建Robot对象
        Robot robot = new Robot("小度");
        Person person = new Person("张三");

        // 创建键盘对象
        Scanner sc = new Scanner(System.in);
        int commend = sc.nextInt();
        System.out.println(robot.toString());
        robot.command(commend);

        System.out.println(person.toString());
        person.eat();
        person.sleep();
        person.work();
    }
}
复制代码

抽象类就像是身份证模板,定义一些方法需要实例化子类去实现,并且在抽象类中可以定义普通方法调用抽象方法。

经供参考

posted on   时间完全不够用啊  阅读(124)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示