【发布时间】:2019-01-24 03:49:52
【问题描述】:
众所周知,父类必须在子类之前构造;并且如果父类的构造函数带参数,那么必须显式调用父类的构造函数。我的问题是,如果子类本身没有构造函数,如何调用从子类显式获取参数的父类构造函数?
public class A {
public String text;
public A(String text) {
this.text = text;
}
}
public class B extends A {
// Now I must call the constructor of A explicitly (other wise I'll get a
// compilation error) but how can I do that without a constructor here?
}
【问题讨论】:
-
为什么你不想在 B 中有一个构造函数?
-
如果您没有说明为什么要在 B 中没有构造函数,这只是一个 XY problem。
-
这只是一种假设情况。
-
感谢您的快速接受,并对 super() 和 super.someMethod() 造成的混淆感到抱歉 :-)
-
@GhostCat 感谢您的回答并澄清每个类都有一个构造函数,即使我没有明确地创建一个。在我意识到我的问题的荒谬之前,我肯定需要了解编译器会自动生成一个。
标签: java inheritance constructor super