Java

Java中super关键字在多层继承中的表现

小樊
84
2024-08-02 21:31:12
栏目: 编程语言

在Java中,当一个类继承自另一个类,而这个另一个类又继承自第三个类,那么在子类中可以使用super关键字来调用父类的构造器或方法。

在多层继承中,如果子类想要调用父类的构造器,可以使用super关键字来实现。例如:

class GrandParent {
    public GrandParent() {
        System.out.println("GrandParent constructor");
    }
}

class Parent extends GrandParent {
    public Parent() {
        super();
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    public Child() {
        super();
        System.out.println("Child constructor");
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

在上面的例子中,当创建Child对象时,会依次调用GrandParent、Parent和Child的构造器,输出如下:

GrandParent constructor
Parent constructor
Child constructor

这样就可以在多层继承中使用super关键字来调用父类的构造器或方法。

0
看了该问题的人还看了