抽象类理解为一种模板
模板模式 使用
package com.example.demo;
/**
* @author dc
* @version 1.0
* @date 2023/03/28 12:55
*/
public abstract class DayPlan {
public abstract void eat();
public abstract void beforeSleep();
public void morning() {
System.out.println ("上班");
}
public void afternoon() {
System.out.println ("下午上班");
}
public void evening() {
System.out.println ("晚上下班");
}
public void sleep() {
System.out.println ("睡觉");
}
public void drink() {
System.out.println ("累了喝点水");
}
public void execute() {
eat ();
morning ();
afternoon ();
drink ();
evening ();
beforeSleep ();
sleep ();
}
}
子类
public class DcPlan extends DayPlan{
@Override
public void eat() {
System.out.println ("面包+牛奶");
}
@Override
public void beforeSleep() {
System.out.println ("玩会手机就睡觉");
}
}
测试
public static void main(String[] args) {
DcPlan plan = new DcPlan ();
plan.execute ();
}
注意事项:
1、抽象类 不能实例化
2、抽象类中包含构造器
3、抽象类中 可以没有抽象方法
4、有抽象方法的类一定是抽象类
5、继承 抽象类时,该类必须是 抽象类或者 重写抽象类中的方法
抽象方法:只有声明,没有方法体
abstract 不能修饰 哪些结构?
1、属性
2、构造器
3、代码块
abstract 不能与哪些关键字共存?
1、不能用 abstract修饰私有方法
2、静态方法
3、被final修饰的 方法
4、被final修饰的 类