子类构造函数 - 为什么子类构造函数必须存在默认构造函数?
给定一个随机类:
public class A<T> {
public T t;
public A () {} // <-- why is this constructor necessary for B?
public A (T t) {
this.setT(t);
}
public T getT () {
return this.t;
}
protected void setT (T t) {
this.t = t;
return;
}
}
和一个扩展类:
public class B extends A<Integer> {
public B (Integer i) {
this.setT(i);
}
}
为什么 B 要求 A 具有空构造函数?我本以为它会想要使用类似的构造函数而不是默认构造函数。我尝试在不使用默认构造函数的情况下进行编译,但在没有默认构造函数的情况下我收到以下消息...
java.lang.NoSuchMethodError: A: method <init>()V not found at B.<init>
任何人都可以解释这是为什么吗?
Given a random class:
public class A<T> {
public T t;
public A () {} // <-- why is this constructor necessary for B?
public A (T t) {
this.setT(t);
}
public T getT () {
return this.t;
}
protected void setT (T t) {
this.t = t;
return;
}
}
And an extended class:
public class B extends A<Integer> {
public B (Integer i) {
this.setT(i);
}
}
Why does B require A to have the empty constructor? I would have assumed it would want to use the similar constructor instead of the default constructor. I tried compiling without the default constructor, but I get the following message without it...
java.lang.NoSuchMethodError: A: method <init>()V not found at B.<init>
Can anyone explain why this is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
重要的一点是要理解任何构造函数的第一行都是调用超级构造函数。如果您自己不调用超级构造函数,编译器会通过在幕后插入
super()
来缩短您的代码。此外,如果您没有任何构造函数,则会自动插入一个空的默认构造函数 - 这里是
A()
或B()
。您可能会遇到这样的情况:您的 B 构造函数中没有
super(...)
,因此编译器会插入super()
调用本身,但您 < em>确实有一个带有参数的 A 构造函数,因此不会插入默认的 A() 构造函数,并且您必须手动提供 A() 构造函数,或者调用 A(i) 构造函数。在这种情况下,我建议只The important point is to understand that the first line of any constructor is to call the super constructor. The compiler makes your code shorter by inserting
super()
under the covers, if you do not invoke a super constructor yourself.Also if you do not have any constructors an empty default constructor - here
A()
orB()
- would automatically be inserted.You have a situation where you do not have a
super(...)
in your B-constructor, so the compiler inserts thesuper()
call itself, but you do have an A-constructor with arguments so the the default A()-constructor is not inserted, and you have to provide the A()-constructor manually, or invoke the A(i)-constructor instead. In this case, I would suggest just having您可以在 A 中使用自己的构造函数,但必须从 B 的构造函数中显式调用它,例如:
如果您不这样做,编译器将尝试实例化 A code> 本身,通过调用其默认构造函数。
You may use your own constructor in
A
, but you have to call it explicitly from the B's constructor, e.g.:If you don't do that, the compiler will attempt to instantiate
A
itself, by calling its default constructor.如果您不使用
super(i)
作为构造函数的第一行来调用超级构造函数,它将隐式调用默认的超级构造函数If you don't make a call to a super constructor using
super(i)
as the first line of your constructor it will implicitly call the default super constructor