Java 继承

extends 关键字、super 的用法、继承的特性与构造方法调用顺序。

Beginner
Key PointsJava 只支持单继承(一个父类),但可以多层继承;子类构造先调父类构造,再执行自己的初始化。

继承的概念

Inheritance lets a subclass reuse the parent's fields and methods, modelling an is-a relationship. Java uses extends, and every class ultimately inherits Object.

Java
class Animal {
    void eat() {
        System.out.println("eating");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("barking");
    }
}

public class InheritDemo {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
        d.bark();
        System.out.println(d instanceof Animal);
    }
}
Output
eating
barking
true

继承的特性

A subclass inherits all non-private members, may add new ones and may override methods. A final class cannot be extended and a final method cannot be overridden.

  • Single inheritance — one parent class only
  • Multilevel — A extends B extends C is fine
  • No multiple class inheritance — use interfaces instead
  • Constructors are not inherited

extends 关键字

class Child extends Parent declares inheritance. Constructing a child runs the parent constructor first, then the child's, so the parent part is fully initialised before use.

Java
class A {
    A() {
        System.out.println("A()");
    }
}

class B extends A {
    B() {
        super();
        System.out.println("B()");
    }
}

public class Order {
    public static void main(String[] args) {
        new B();
    }
}
Output
A()
B()

super 关键字

super.method() calls the overridden parent version, super.field reads a parent field, and super(...) invokes the parent constructor — it must be the first statement.

Java
class Person {
    String name = "person";

    void hello() {
        System.out.println("hello from Person");
    }
}

class Student extends Person {
    String name = "student";

    @Override
    void hello() {
        super.hello();
        System.out.println("hello from Student");
    }

    void show() {
        System.out.println(name);
        System.out.println(super.name);
    }
}

public class SuperDemo {
    public static void main(String[] args) {
        Student s = new Student();
        s.hello();
        s.show();
    }
}
Output
hello from Person
hello from Student
student
person

implements 与继承的区别

extends inherits one class (is-a); implements fulfils interfaces, several at once (can-do). They combine as class A extends B implements C, D.

Java
interface Swimmer {
    void swim();
}

class Bird {
    void fly() {
        System.out.println("flying");
    }
}

class Duck extends Bird implements Swimmer {
    @Override
    public void swim() {
        System.out.println("swimming");
    }
}

public class Both {
    public static void main(String[] args) {
        Duck d = new Duck();
        d.fly();
        d.swim();
        System.out.println(d instanceof Bird);
        System.out.println(d instanceof Swimmer);
    }
}
Output
flying
swimming
true
true

Friends & Partners