java - 为什么在我说 new House ("x "时调用父类(super class)构造函数 Building() )?

标签 java oop inheritance

我有以下代码,但我不明白为什么当我运行它时它会在打印 "h hn x" 之前打印 "b"。为什么 "b" 会被打印出来,因为我在执行 House() 时根本没有调用父类(super class) Building

class Building {
    Building() {
        System.out.print("b ");
    }

    Building(String name) {
        this();
        System.out.println("bn " + name);
    }
}

public class House extends Building {
    House() {
        System.out.println("h ");
    }

    House(String name) {
        this();
        System.out.println("hn " + name);
    }

    public static void main(String[] args) {
        new House("x ");
    }
}

最佳答案

父类(super class)的零参数构造函数由其子类的构造函数自动隐式调用。

更一般地,对于

class B extends A

构造函数

public B()
{
    //Your code
}

其实很像

public B()
{
    super(); //Call the superclass constructor
    //Your code
}

您可以通过显式 调用某些其他父类(super class)构造函数来覆盖此行为。请注意,如果无法对构造函数进行隐式调用(例如,如果您的无参数构造函数不存在),那么您将看到一个错误。

关于java - 为什么在我说 new House ("x "时调用父类(super class)构造函数 Building() )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28325816/

相关文章:

java - 将电话号码或 CONTACT_ID 从 Android 联系方式传递到 Activity (类似 Whatsapp)

java - Spring RestTemplate 将大文件转发到另一个服务

search - 存储和搜索对象事务的最佳方式是什么?

python - 为什么我的 Python 代码中会出现 TypeError?

ios - 允许用户创建表单的应用程序

c++ - 虚拟继承和静态继承——C++中的混合

java - 如何使用Hibernate创建实体来创建具有两个外键列的表: No identifier specified for entity:

java - JFormattedTextField 破坏 DocumentFilter

python - Python 数据类的子级总是数据类本身吗?

javascript - 管理 JS 继承失败