首页 > 解决方案 > 如果我们在父类构造函数中添加一个 super(),这个 super() 在创建子类的对象时会调用哪个类?

问题描述

在下面的示例中,super() 将在创建 Square 对象时在 Shape 构造函数中调用哪个类?

package com.company;

class Shape {
    public Shape() {
        super();
        System.out.println("inside Shape class default constructor");
    }
}

class Rectangle extends Shape {
    public Rectangle() {
        super();
        System.out.println("inside Rectangle class default constructor");
    }
}

class Square extends Rectangle {
    public Square() {
        super();
        System.out.println("inside Square class default constructor");
    }
}

public class Ex2 {
    public static void main(String[] args) {
        Square sq = new Square();
    }
}

标签: javaloopsinheritance

解决方案


它将调用java.lang.Object类的构造函数,它是 Java 中所有类的默认父级。


推荐阅读