抽象类与抽象方法

  • 抽象类可以没有抽象方法,但是有抽象方法的类一定是抽象类,抽象类是不能new的。
  • 当一个类继承抽象类,必须重写父类中的所有抽象方法,否则无法被实例化,除非该类也是抽象类。

在模板方法模式中的应用

使用抽象类,定义抽象方法,从而达成对子类的约束。

public abstract class Beverage {
    // 模板方法
    public final void prepareRecipe() {
        boilWater();
        brew();
        pourInCup();
        addCondiments();
    }

    // 公共方法
    private void boilWater() {
        System.out.println("Boiling water...");
    }

    private void pourInCup() {
        System.out.println("Pouring into cup...");
    }

    // 抽象方法,子类必须实现
    protected abstract void brew();

    protected abstract void addCondiments();
}
public class Coffee extends Beverage {
    @Override
    protected void brew() {
        System.out.println("Brewing coffee...");
    }

    @Override
    protected void addCondiments() {
        System.out.println("Adding sugar and milk...");
    }
}
public class Tea extends Beverage {
    @Override
    protected void brew() {
        System.out.println("Steeping the tea...");
    }

    @Override
    protected void addCondiments() {
        System.out.println("Adding lemon...");
    }
}
package org.example;

public class Main {
    public static void main(String[] args) {
Beverage coffee = new Coffee();
        Beverage tea = new Tea();

        System.out.println("\nMaking coffee:");
        coffee.prepareRecipe();

        System.out.println("\nMaking tea:");
        tea.prepareRecipe();
    }
}