gpt4 book ai didi

java - 这个子类是如何隐式调用父类的构造函数的呢?

转载 作者:行者123 更新时间:2023-11-30 07:04:39 26 4
gpt4 key购买 nike

我有这两个类:

public class Document {
private static int quantity = 0;
public Document() {
quantity = quantity + 1;
}
public static int getQuantity() {
return quantity;
}
}

public class Book extends Document {
private int numChapters;
public Book(int numChapters) {
this.numChapters = numChapters;
}
public static void main(String[] args) {
Book b1 = new Book(4);
Book b2 = new Book(6);
Document d1 = new Document();
System.out.println(Document.getQuantity());
}
}

这里的程序返回 3,但我希望它返回 1。有人能告诉我代码中发生了什么吗?似乎在创建 b1 和 b2 时隐式调用了父类的构造函数。据我了解,子类不继承其父类的构造函数。

最佳答案

参见 docs :

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

你有一个自动调用的无参数构造函数。

这种行为是有道理的,构造函数是用来创建对象的。所以它应该包含其类的正确初始化代码。如果您的类(class)扩展了另一个类(class)怎么办?它不应该包含构造该对象所需的所有代码吗?

关于java - 这个子类是如何隐式调用父类的构造函数的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com