"this" 子类构造函数上的关键字是否需要隐式定义超类默认构造函数?
does "this" keyword on subclass constructor requires superclass default constructor to be implicitly defined?
以下代码需要隐式定义超类构造函数才能使此关键字起作用
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.
编译错误显示在三个子构造函数中
参数.
- 此关键字是否需要隐式定义 SuperClass 构造函数。
问题是 Parent
没有默认构造函数。那么如果有人想通过 Child(String s, String s1, String s3)
构造函数创建一个 child 实例, Parent
将如何实例化?
这与构造函数链接 (this()
) 没有明确的关系。您在 Child(String s, String s1)
中没有收到错误的原因是因为您实际上是通过 this(s,s1,"hello");
[构造函数链接]
调用 super(i,n);
因此您需要描述一种在最后一个构造函数中创建父级 class 的方法,方法是直接在其中调用 super
或通过构造函数链传递或创建 [= 的默认构造函数10=].
以下代码需要隐式定义超类构造函数才能使此关键字起作用
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.
编译错误显示在三个子构造函数中 参数.
- 此关键字是否需要隐式定义 SuperClass 构造函数。
问题是 Parent
没有默认构造函数。那么如果有人想通过 Child(String s, String s1, String s3)
构造函数创建一个 child 实例, Parent
将如何实例化?
这与构造函数链接 (this()
) 没有明确的关系。您在 Child(String s, String s1)
中没有收到错误的原因是因为您实际上是通过 this(s,s1,"hello");
[构造函数链接]
super(i,n);
因此您需要描述一种在最后一个构造函数中创建父级 class 的方法,方法是直接在其中调用 super
或通过构造函数链传递或创建 [= 的默认构造函数10=].