随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。

类一:

// 抽象类
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 2022-01-23 23:38  时间完全不够用啊  阅读(107)  评论(0编辑  收藏  举报