简体   繁体   English

错误:无法从静态上下文引用非静态变量super >>但是我使用static关键字

[英]Error: Non-static variable super cannot be referenced from a static context >>but i use static keyword

How can i refers to "a1" from superclass (class "aa") with "super" keyword 我如何用“ super”关键字引用超类(“ aa”类)中的“ a1”

class aa {
protected static int a1 = 2;
}

public class bb extendeds aa {
static int a1 = 3;
public static int s = super.a1;
}

The static members of a class belong to a class and not to a particular instance. 类的static成员属于类,而不属于特定实例。

When you invoke super.member you are trying to access the member of the current instance inherited from the parent class. 调用super.member您尝试访问的是从父类继承的当前实例member It is done so because the same member might be shadowed in the child class, so super will refer to the member in the parent class. 这样做是因为同一个成员可能在子类中被遮蔽,所以super将引用父类中的成员。

So in a static context it is ambiguous that from which instance the member is going to be initialised with a value. 因此,在static上下文中,模棱两可的是该成员将从哪个实例初始化为一个值。 In fact static members can be accessed when no instances exist. 实际上,当不存在实例时,可以访问静态成员。 So the usage of super in a static context (method or in your case a field) is not possible and the compiler throws an error. 因此,不可能在静态上下文(方法或您的情况下为字段)中使用super ,并且编译器会引发错误。

Furthermore the static fields are initialised when the class is loaded at which point no instance variables are initialised. 此外,在加载类时会初始化静态字段,此时将不会初始化实例变量。 So initialising with super.member makes no sense. 因此,用super.member初始化是没有意义的。

From JLS : 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. 形式super.Identifier引用当前对象的名为Identifier的字段,但是将当前对象视为当前类的超类的实例。

You need to modify your code to: 您需要将代码修改为:

public class bb extendeds aa {
   static int a1 = 3;
   public static int s = aa.a1; //a1 belongs to class aa not to an instance
}

If you really want to use super instead of just doing aa.a1 , you can technically do this in the constructor without error and only get a warning: 如果您真的想使用super而不是仅仅使用aa.a1 ,那么从技术 aa.a1 ,您可以在构造函数中做到这一点而不会出现错误,并且只会得到警告:

public static int s;

public bb(){
    this.s = super.a1;
}

Test Run: 测试运行:

aa a = new aa();
bb b = new bb();
System.out.println(a.a1);
System.out.println(b.s);

Output: 输出:

2 2

2 2

I really do not recommend doing this and try to avoid using static with objects or just use static like a static field if you really do need one. 我真的不建议这样做,并尽量避免对对象使用static ,或者如果确实需要使用staticstatic字段一样使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM