子类构造函数上的“this”关键字是否要求隐式定义超类默认构造函数?
下面的代码需要隐式定义超类构造函数,才能使该关键字工作
public class SuperEx {
public static void main(String[] args) {
// TODO Auto-generated method stub
Child c=new Child(10,"AK");
c=new Child("Hi","AK");
}
}
class Parent{
int n;
String s;
Parent(int n, String s){
this.n=n;
this.s=s;
System.out.println("Parent constructor arg value is "+n +" and " +s);
}
}
class Child extends Parent{
Child(int i, String n){
super(i,n);
System.out.println("child 2nd Constructor");
}
Child(String s, String s1){
this(s,s1,"hello");
}
/*here im getting error in eclipse IDE which says "Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor*/
Child(String s, String s1, String s3){
System.out.println("values are "+s+" "+s1+" "+s3);
}
}
上面的代码是在eclipse neon ide中键入的
编译错误显示在子构造函数中,有三个 争论
- 该关键字是否要求隐式定义超类构造函数李>
# 1 楼答案
问题是
Parent
没有默认构造函数。因此,如果有人想通过Child(String s, String s1, String s3)
构造函数创建child的实例,那么Parent
将如何实例化这与构造函数链接(
this()
)没有明确的关系。在Child(String s, String s1)
中没有出现错误的原因是,您实际上是通过this(s,s1,"hello");
[构造函数链接]调用super(i,n);
因此,您需要描述一种在最后一个构造函数中创建父类的方法,可以直接在其中调用
super
,也可以通过构造函数链传递,或者创建一个默认的Parent
构造函数