gpt4 book ai didi

java - 错误: Non-static variable super cannot be referenced from a static context >>but i use static keyword

转载 作者:行者123 更新时间:2023-12-02 09:35:03 26 4
gpt4 key购买 nike

我如何使用“super”关键字从父类(super 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.member时,您正在尝试访问从父类继承的当前实例member。这样做是因为同一个成员可能会在子类中被隐藏,因此 super 将引用父类中的成员。

因此,在静态上下文中,从哪个实例成员将被初始化为值是不明确的。事实上,当不存在实例时,可以访问静态成员。因此,在静态上下文(方法或在您的情况下为字段)中使用 super 是不可能的,编译器会抛出错误。

此外,静态字段在类加载时初始化,此时没有实例变量被初始化。因此用 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
}

关于java - 错误: Non-static variable super cannot be referenced from a static context >>but i use static keyword,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57591129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com