【发布时间】:2014-06-05 10:46:39
【问题描述】:
-
1234563子类如何调用它的超类构造函数?
这种情况下是否使用
super()的默认构造函数?
或
- 仅当没有调用
this()或super()作为子类的第一行时才使用默认构造函数?
【问题讨论】:
标签: java inheritance constructor super
这种情况下是否使用super()的默认构造函数?
或
this() 或super() 作为子类的第一行时才使用默认构造函数? 【问题讨论】:
标签: java inheritance constructor super
super contructor,除了超级有一个没有参数的“可见”构造函数。样本:
父构造函数:
public Parent();
public Parent(int x, int y);
子构造函数:
public Child() {
// invokes by default super() if there is no other super call.
}
public Child(int x, int y) {
// invokes by default super() if there is no other super call.
}
但是如果你将父构造函数定义为私有:
父构造函数:
private Parent();
public Parent(int x, int y);
子构造函数:
public Child() {
// does not compile due there is no "visible" super().
}
public Child(int x, int y) {
// does not compile due there is no "visible" super().
}
你需要直接调用超级构造函数
public Child() {
super(1,2);
}
public Child(int x, int y) {
super(x,y);
}
【讨论】:
从 SubClass 构造函数中调用 SuperClass 构造函数的方式如下。
1 SuperClass 没有默认构造函数,这意味着 SuperClass 有一个带参数的构造函数。例如
SuperClass(int a){
//somethin
}
您必须从子类构造函数中显式调用超类构造函数,否则您的程序将无法编译。前任。
Subclass(){
super(10);
}
2 > SuperClass 有一个默认构造函数,它可以不定义任何构造函数,也可以定义一个默认构造函数。在这种情况下,您不需要从子类 1 调用超级构造函数,但如果您愿意,可以通过调用来调用。
Subclass(){
super();
}
请记住,您只能从任何构造函数调用另一个构造函数。 例如。
SubClass(){
super();
this(10);//this will not compile either you can call this or super
}
【讨论】: