java - 如何强制我的子类构造函数不调用基类构造函数?

标签 java

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/

相关文章:

java - 为什么 Goetz 不再在代码 list 7.20 中使用 volatile boolean 呢?

java - Maven 编译器插件不支持的类文件主要版本 60

Java 编程 : Turtle not moving in desired direction

java - 有没有办法在 IntelliJ 中使用 "deprecate"库方法?

java - 为什么我不能从 ArrayList 中获取值?

java - 无法在 ActionListener 中重新绘制

java - 错误:HttpHostConnectionException

java - 如何在java中使用已弃用的导入?

java - 使用 AssetManager 时位图字体倒置

java - 在 dom 树的第一个 child 之前添加一个新节点