【问题标题】:Java - Constructor does not explicitly invoke a superclass constructor, Java does not insert one eitherJava - 构造函数没有显式调用超类构造函数,Java 也没有插入一个
【发布时间】:2014-08-16 12:48:35
【问题描述】:

首先,这是我在docs.oracle.com上看到的内容

注意:如果构造函数没有显式调用超类构造函数,Java 编译器会自动插入对超类的无参数构造函数的调用。如果超类没有无参数构造函数,则会出现编译时错误。 Object 确实有这样的构造函数,所以如果 Object 是唯一的超类,没有问题。

但是当我测试我的代码时,class B 的无参数构造函数 没有超类构造函数并且 Java 没有添加一个。这是为什么?这是我所期望的:

   public B(){
        super(); //<--- Why didn't Java add this superclass constructor? 
        this(false);
        System.out.println("b1");
    }

这是否与“public B()”构造函数调用另一个构造函数而调用另一个具有超类构造函数的构造函数有关?

我得到的输出是:a2 a1 b2 b3 b1 c1 a2 a1 b2 b3 b1 c1 c2

public class App {
    public static void main(String[] args){
        new C();
        new C(1.0);
    }
}

A类

public class A {
    public A(){
        this(5);
        System.out.println("a1");
    }

    public A(int x){
        System.out.println("a2");
    }
}

B类

public class B extends A {
    public B(){
        this(false);
        System.out.println("b1");
    }

    public B(int x){
        super();
        System.out.println("b2");
    }

    public B(boolean b){
        this(2);
        System.out.println("b3");
    }
}

C类

public class C extends B {
    public C(){
        System.out.println("c1");
    }

    public C(double x){
        this();
        System.out.println("c2");
    }
}

【问题讨论】:

  • 输出的哪一部分是您不期望的?
  • 我曾期望它以 [a2 a1 a2 a1 a2 a1..] 开头,因为我认为编译器会在 B 类的第一个和第三个构造函数中添加 super()。什么 @Mureinik说的有道理,谢谢!

标签: java class inheritance constructor superclass


【解决方案1】:

this(args) 的调用在其他任何事情之前进行评估。所以B() 调用B(boolean),后者调用B(int),后者显式调用super()

【讨论】:

  • +1 如果它不能以这种方式工作,super() 将被调用两次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 2015-07-02
相关资源
最近更新 更多