Java 是不是;这";子类构造函数上的关键字要求隐式定义超类默认构造函数?
下面的代码需要隐式定义超类构造函数,才能使该关键字工作Java 是不是;这";子类构造函数上的关键字要求隐式定义超类默认构造函数?,java,inheritance,constructor,this,super,Java,Inheritance,Constructor,This,Super,下面的代码需要隐式定义超类构造函数,才能使该关键字工作 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; Str
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);
}
}
问题是父级
没有默认构造函数。因此,如果有人想通过child(字符串s、字符串s1、字符串s3)
构造函数创建child的实例,将如何实例化Parent
这与构造函数链接无关(This()
)。在Child(字符串s,字符串s1)
中没有出现错误的原因是因为您实际上正在调用super(i,n)代码>通过此(s,s1,“你好”)代码>[构造函数链接]
因此,您需要描述一种在最后一个构造函数中创建父类的方法,可以直接在其中调用super
,也可以通过构造函数链接传递,或者创建parent
的默认构造函数。问题是parent
没有默认构造函数。因此,如果有人想通过child(字符串s、字符串s1、字符串s3)
构造函数创建child的实例,将如何实例化Parent
这与构造函数链接无关(This()
)。在Child(字符串s,字符串s1)
中没有出现错误的原因是因为您实际上正在调用super(i,n)代码>通过此(s,s1,“你好”)代码>[构造函数链接]
因此,您需要描述一种在最后一个构造函数中创建父类的方法,可以直接在其中调用super
,也可以通过构造函数链接传递,或者创建parent
的默认构造函数。您的问题与调用this(…)的构造函数无关
。您的问题与调用此(…)的构造函数无关。
。