作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这两个类:
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/
我是一名优秀的程序员,十分优秀!