如果在构造函数链接场景中,我想使用参数化 super()
在子类构造函数中调用父类(super class)的参数化构造函数之前 this()
那怎么编码呢??
因为父类(super class)默认构造函数会自动调用而不提及 super()
之前this()
在子类构造函数中,但如果我想调用参数化构造函数,在 super()
中给出参数那怎么办?因为明确地它不允许提及 super()
之前this()
。
请回复,提前致谢。
class Parent {
Parent() {
System.out.println("Welcome in Parent class'Default Constructor");
}
Parent(int x) {
System.out.println("Welcome in Parent class'Parameterized Constructor");
System.out.println("Your Lucky no.is: "+x);
}
}
class Child extends Parent
{
{
System.out.println("I am in init block.");
}
Child()
{
// super(7); ERROR!!
this(10);
System.out.println("I am in constructor Child()");
}
Child(int x)
{
this(20,30);
System.out.println("I am in constructor Child(int x)");
}
Child(int x,int y)
{
System.out.println("I am in constructor Child(int x, int y)");
}
public static void main(String arg[])
{
System.out.println("I am in main");
new Child();
System.out.println("Again I am in main");
}
}
}
最佳答案
构造函数无论是隐式还是显式都不能同时使用 super()
和 this()
调用。您可以链接到父类(super class)构造函数 (super()
),也可以链接到同一个类构造函数(使用 this()
)。
因此,如果您想调用参数化父类(super class)构造函数,只需执行此操作,而无需提及 this()
调用。它会起作用的。
关于使用 this() 的 Java 构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29644586/