-
如果你有一个子类,而你的仅子类构造函数是
super(int x, int y)
,但该参数结构与它的任何超类构造函数的参数结构都不匹配,那么会发生什么?子类如何调用它的超类构造函数? -
在这种情况下是否使用
super()
的默认构造函数?
或
- 是否只有在没有调用
this()
或super()
作为子类的第一行时才使用默认构造函数
- 您必须直接调用您喜欢的
super contructor
,除非super有一个不带参数的"可见"构造函数 - 只有当它是可访问的(公共的或受保护的(并且没有其他构造函数与其签名匹配时
样本:
父构造函数:
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);
}
SuperClass构造函数是按照以下模式从SubClass构造函数调用的。
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
}