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

   2024-10-02 3270
核心提示:在Java中,当一个类继承自另一个类,而这个另一个类又继承自第三个类,那么在子类中可以使用super关键字来调用父类的构造器或方

在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 constructorParent constructorChild constructor

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号