Java 抽象类

abstract 关键字、抽象类的规则、继承抽象类与模板方法模式。

Intermediate
Key Points含抽象方法的类必须声明为 abstract;抽象类不能实例化,但可以有构造方法、普通方法和字段。

抽象类

abstract class is an incomplete class defining a skeleton and leaving details to subclasses. It cannot be instantiated, but you can declare references and extend it.

Java
abstract class Employee {
    String name;

    Employee(String name) {
        this.name = name;
    }

    abstract double salary();

    void printInfo() {
        System.out.println(name + " earns " + salary());
    }
}

class FullTime extends Employee {
    FullTime(String name) {
        super(name);
    }

    @Override
    double salary() {
        return 8000;
    }
}

public class AbstractDemo {
    public static void main(String[] args) {
        Employee e = new FullTime("Tom");
        e.printInfo();
    }
}
Output
Tom earns 8000.0

抽象方法

An abstract method has a declaration only, ending with a semicolon. Subclasses must implement every abstract method or be declared abstract themselves.

Java
abstract class Shape {
    abstract double area();

    abstract String name();
}

class Rect extends Shape {
    double w = 2, h = 3;

    @Override
    double area() {
        return w * h;
    }

    @Override
    String name() {
        return "rect";
    }
}

public class AbsMethod {
    public static void main(String[] args) {
        Rect r = new Rect();
        System.out.println(r.name() + " " + r.area());
    }
}
Output
rect 6.0

继承抽象类

A subclass extends with extends and still calls the parent constructor first. Abstract classes may mark methods final to lock behaviour while leaving others open for customisation.

Java
abstract class Template {
    final void run() {
        step1();
        step2();
    }

    void step1() {
        System.out.println("step1 default");
    }

    abstract void step2();
}

class Impl extends Template {
    @Override
    void step2() {
        System.out.println("step2 custom");
    }
}

public class TemplateDemo {
    public static void main(String[] args) {
        new Impl().run();
    }
}
Output
step1 default
step2 custom

抽象类与接口的区别

An abstract class is is-a, single inheritance, may hold state and constructors. An interface is can-do, multiply implementable, with implicitly public static final fields. Share state with abstract classes, share capability with interfaces.

AspectAbstract classInterface
Keywordextendsimplements
How manyOneMany
StateInstance fields allowedConstants only
ConstructorYesNo
MethodsAbstract or concreteAbstract, default, static

Friends & Partners