Error: Non-static variable super cannot be referenced from a static context >>but i use static keyword
Error: Non-static variable super cannot be referenced from a static context >>but i use static keyword
如何使用 "super" 关键字
从 superclass (class "aa") 引用 "a1"
class aa {
protected static int a1 = 2;
}
public class bb extendeds aa {
static int a1 = 3;
public static int s = super.a1;
}
如果你真的想使用super
而不只是aa.a1
,你可以技术上做这在构造函数中没有错误,只收到警告:
public static int s;
public bb(){
this.s = super.a1;
}
测试运行:
aa a = new aa();
bb b = new bb();
System.out.println(a.a1);
System.out.println(b.s);
输出:
2
2
我真的不建议这样做,并尽量避免将 static
与对象一起使用,或者如果您确实需要一个字段,则只使用 static
作为 static
字段。
class 的 static
成员属于 class 而不是特定实例。
当您调用 super.member
时,您正在尝试访问从父 class 继承的当前 实例 的 member
。这样做是因为同一个成员可能会隐藏在子 class 中,因此 super
将引用父 class.
中的成员
因此在 static
上下文中,成员将从哪个 实例 初始化为一个值是不明确的。事实上,当不存在实例时,可以访问静态成员。因此,在静态上下文(方法或您的情况下为字段)中使用 super
是不可能的,编译器会抛出错误。
此外,静态字段在 class 加载时初始化,此时没有实例变量被初始化。所以用 super.member
初始化是没有意义的。
来自JLS:
The form super.Identifier refers to the field named Identifier of the
current object, but with the current object viewed as an instance of
the superclass of the current class.
您需要将代码修改为:
public class bb extendeds aa {
static int a1 = 3;
public static int s = aa.a1; //a1 belongs to class aa not to an instance
}
如何使用 "super" 关键字
从 superclass (class "aa") 引用 "a1"class aa {
protected static int a1 = 2;
}
public class bb extendeds aa {
static int a1 = 3;
public static int s = super.a1;
}
如果你真的想使用super
而不只是aa.a1
,你可以技术上做这在构造函数中没有错误,只收到警告:
public static int s;
public bb(){
this.s = super.a1;
}
测试运行:
aa a = new aa();
bb b = new bb();
System.out.println(a.a1);
System.out.println(b.s);
输出:
2
2
我真的不建议这样做,并尽量避免将 static
与对象一起使用,或者如果您确实需要一个字段,则只使用 static
作为 static
字段。
class 的 static
成员属于 class 而不是特定实例。
当您调用 super.member
时,您正在尝试访问从父 class 继承的当前 实例 的 member
。这样做是因为同一个成员可能会隐藏在子 class 中,因此 super
将引用父 class.
因此在 static
上下文中,成员将从哪个 实例 初始化为一个值是不明确的。事实上,当不存在实例时,可以访问静态成员。因此,在静态上下文(方法或您的情况下为字段)中使用 super
是不可能的,编译器会抛出错误。
此外,静态字段在 class 加载时初始化,此时没有实例变量被初始化。所以用 super.member
初始化是没有意义的。
来自JLS:
The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.
您需要将代码修改为:
public class bb extendeds aa {
static int a1 = 3;
public static int s = aa.a1; //a1 belongs to class aa not to an instance
}