sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-02 09:35:03 28 4
mua khóa gpt4 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;
}

1 Câu trả lời

类的静态成员属于一个类而不是特定的实例。

当您调用super.member时,您正在尝试访问从父类继承的当前Ví dụcủamember。这样做是因为同一个成员可能会在子类中被隐藏,因此 siêu 将引用父类中的成员。

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

此外,静态字段在类加载时初始化,此时没有实例变量被初始化。因此用 super.member 初始化是没有意义的。

Từ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/

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com