为什么在下面的代码中没有调用 super class 的参数化构造函数?
Why the parameterised constructor of the super class is not called in the following code?
class demo1
{
demo1(int x){
System.out.println("This is super class constructor!");
}
}
public class demo extends demo1
{
int y;
demo()//or if i do: demo(int y)
{
super(y);
System.out.print(4);
}
public static void main(String args[]){
demo d = new demo();
}
出现以下错误
demo.java:13: 错误:在调用超类型构造函数之前无法引用 y
超级(y);
^
1 个错误
子class实例变量y
仅在调用超class构造函数后才被初始化。因此它不能在对超级 class 构造函数的调用中被引用。
即使允许,super(y);
调用在您的示例中也没有任何意义,因为它没有将任何有意义的数据传递给超级 class 构造函数(因为您没有分配y
成员的任何内容)。传递给子 class 构造函数的超 class 构造函数参数或常量值才有意义。
例如下面会通过编译:
public class Demo extends Demo1
{
int y;
Demo (int y) {
super(y); // here y is the argument passed to the Demo constructor, not the
// instance variable of the same name
System.out.print(4);
}
public static void main(String args[]) {
Demo d = new Demo(10);
}
}
class demo1
{
demo1(int x){
System.out.println("This is super class constructor!");
}
}
public class demo extends demo1
{
int y;
demo()//or if i do: demo(int y)
{
super(y);
System.out.print(4);
}
public static void main(String args[]){
demo d = new demo();
}
出现以下错误
demo.java:13: 错误:在调用超类型构造函数之前无法引用 y 超级(y); ^ 1 个错误
子class实例变量y
仅在调用超class构造函数后才被初始化。因此它不能在对超级 class 构造函数的调用中被引用。
即使允许,super(y);
调用在您的示例中也没有任何意义,因为它没有将任何有意义的数据传递给超级 class 构造函数(因为您没有分配y
成员的任何内容)。传递给子 class 构造函数的超 class 构造函数参数或常量值才有意义。
例如下面会通过编译:
public class Demo extends Demo1
{
int y;
Demo (int y) {
super(y); // here y is the argument passed to the Demo constructor, not the
// instance variable of the same name
System.out.print(4);
}
public static void main(String args[]) {
Demo d = new Demo(10);
}
}