当前正在对抽象类和接口进行实践测试,并遇到了这个问题:

  public class Test {
  public static void main(String[] args) {
    new Circle9();
  }
}

public abstract class GeometricObject {
  protected GeometricObject() {
    System.out.print("A");
  }

  protected GeometricObject(String color, boolean filled) {
    System.out.print("B");
  }
}

public class Circle9 extends GeometricObject {
  /** Default constructor */
  public Circle9() {
    this(1.0);
    System.out.print("C");
  }

  /** Construct circle with a specified radius */
  public Circle9(double radius) {
    this(radius, "white", false);
    System.out.print("D");
  }

  /** Construct a circle with specified radius, filled, and color */
  public Circle9(double radius, String color, boolean filled) {
    super(color, filled);
    System.out.print("E");
  }


}

为什么输出BEDC?我以为新的Circle9()首先会调用Circle 9类的no-arg构造函数,先打印A,然后再打印其他字母,但是我很难理解代码的路径。

最佳答案

遵循调用堆栈:


新的Circle9()调用Circle9()
Circle9()称为this(1.0)
Circle9(double)称这个(半径,“ white”,false)
Circle9(double,String,boolean)调用super(color,fill)
GeometricObject(String,boolean)打印B
Circle9(double,String,boolean)打印E
Circle9(双)打印D
Circle9()打印C

10-02 00:06