Java 简单抽象类的应用小🌰

package com.jasonote.classStudy;

/**
 * Created by Jasonote on 2017/11/26.
 * 抽象类的应用
 */
abstract class Action {
    public static final int EAT = 1;
    public static final int WORK = 2;
    public static final int SLEEP = 3;
    public static final int PLAY = 4;

    public void cron(int flag) {
        switch (flag) {
            case EAT:
                this.eat();
                break;
            case WORK:
                this.work();
                break;
            case SLEEP:
                this.sleep();
                break;
            case PLAY:
                this.play();
                break;
            case EAT + PLAY:
                this.eat();
                this.play();
                break;
            default:
                break;
        }
    }

    abstract void eat();

    abstract void work();

    abstract void sleep();

    abstract void play();

}

class BritishShorthairCat extends Action {

    @Override
    void eat() {
        System.out.println("BritishShorthairCat 在吃猫粮 ~");
    }

    @Override
    void work() {

    }

    @Override
    void sleep() {
        System.out.println("BritishShorthairCat 在打呼呼 ~");
    }

    @Override
    void play() {
        System.out.println("BritishShorthairCat 在玩耍 ~");
    }
}

class Jasonote extends Action {
    @Override
    void eat() {
        System.out.println("Jasonote 正在吃火锅~");
    }

    @Override
    void work() {
        System.out.println("Jasonote 正在码代码~");
    }

    @Override
    void sleep() {
        System.out.println("Jasonote 在睡觉呢~");
    }

    @Override
    void play() {
        System.out.println("Jasonote 正在打游戏~");
    }
}

public class AbstractClassDemo {

    public static void main(String[] args) {
        fun(new Jasonote());
        System.out.println("------------------");
        fun(new BritishShorthairCat());
    }

    public static void fun(Action act) {
        act.cron(Action.WORK);
        act.cron(Action.EAT);
        act.cron(Action.PLAY + Action.EAT);
        act.cron(Action.SLEEP);
    }
}



Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...