我在编写程序时遇到了一些意想不到的结果。我有三个类,它们都可以正确编译,但是当我运行它们时,它们似乎没有将正确的输出写入控制台。根据我的主要方法,我应该得到一个显示的结果:
Extender called
ClassTest called
但是,它正在写:
AbsClass called
Extender called
ClassTest called
我在 ClassTest 类构造函数中使用了 super()
,但这应该只调用父类,对吗?
这是第一个类:
public abstract class AbsClass {
public AbsClass() {
System.out.println("AbsClass called");
}
}
这是第二堂课:
public class Extender extends AbsClass {
public Extender() {
System.out.println("Extender called");
}
}
这是带有 main 方法的最后一个类:
public class ClassTest extends Extender {
public ClassTest() {
super();
System.out.println("ClassTest called");
}
public static void main(String[] args){
ClassTest test = null;
test=new ClassTest();
}
}
最佳答案
如果您的构造函数不是以显式调用 this()
或 super()
开头,则编译器会自动插入对默认父类(super class)的调用构造函数。来自 Java Language Specification (§8.8.7) :
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
因此,当 Extender
的构造函数开始执行时,将调用默认构造函数 AbsClass()
。
关于java - 主要调用太多类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22050249/