繁体   English   中英

关于超类和子类的构造函数的问题

[英]Question about constructor of superclass and subclass

为什么代码 (1) 不会导致错误,而代码 (2) (3) 会?

我认为当子类调用构造函数时,它会首先调用超级 class 构造函数,但我不知道为什么代码(1)是对的而其他两个是错误的。

//(1)

public class Parent {
  public int a;

  public Parent() {
    this.a = 0;
  }
}

public class Child extends Parent {
  public Child() {}
}

//(2)

public class Parent {
  public int a;

  public Parent(int number) {
    this.a = number;
  }
}

public class Child extends Parent {
  public Child() {}
}

//(3)

public class Parent {
  public int a;

  public Parent(int number) {
    this.a = number;
  }
}

public class Child extends Parent {
  public Child(int numb) {      
  }
}

代码(1)是正确的,而其他两个是错误的。

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

因此,在这里,您的代码 (2)(3) 没有无参数构造函数,而且您没有显式调用具有参数的构造函数,因此出现编译时错误。 更多细节来自https://docs.oracle.com/javase/tutorial/java/IandI/super.html

在代码 1 中, Parent的构造函数没有 arguments,因此对默认构造函数的调用是隐式的:

public Child () {
    super();
} /* This code is not necessary, but is implied. */

但是在代码 2 和 3 中,构造函数有一个参数,并且由于没有提供无参数的重载,因此必须提供对超类构造函数的调用。 为此,您必须引用super()

public class Parent {
    public int a;

    public Parent(int number) {
        this.a = number;
    }
}

public class Child extends Parent {
    public Child(int numb) {
        super(numb); // Calls Parent(int) and sets this instance’s Parent.a value to numb.
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM