public class Base {
public Base() {
foo();
}
public void foo() {
System.out.println("Base.foo()");
}
}
public class Derived extends Base {
public Derived () {}
public void foo() {
System.out.println("Derived.foo()");
}
}
然后,当我调用它们时:
public class Running {
public static void main(String[] args) {
Base b = new Base();
Derived d = new Derived();
}
}
它输出:
*Base.foo()*
*Derived.foo()*
那么为什么当它到达派生构造函数时,它会调用基构造函数,但使用派生函数的方法呢?
PS:如果我将这些方法标记为私有(private),它将打印出:
*Base.foo()*
*Base.foo()*
最佳答案
这就是 Java 的工作原理阅读此页 https://docs.oracle.com/javase/tutorial/java/IandI/super.html
更具体地说,这里的注释:
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.
正如您所看到的,这是预期的行为。即使您没有 super 调用,它仍然会自动插入它。
关于第二个问题,即使您位于 super 构造函数体内,您的实例仍然属于子类型。另外,如果您对 C++ 有一定的了解,请阅读此 Can you write virtual functions / methods in Java?
之所以用private标记时会写基类,是因为私有(private)方法不是继承的。这是 Java 中的继承主题的一部分。
关于java - 如何强制我的子类构造函数不调用基类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291193/