gpt4 book ai didi

java - Java 中来自静态上下文的模糊调用

转载 作者:太空狗 更新时间:2023-10-29 22:39:46 26 4
gpt4 key购买 nike

main 方法尝试访问 var,但导致调用不明确。为什么? Base1 中的实例变量 var 无论如何都无法从静态上下文访问(可见?)。

  class Base1 {
int var;
}

interface Base2 {
public static final int var = 0;
}

class Test extends Base1 implements Base2 {
public static void main(String args[]) {
System.out.println("var:" + var);
}
}

最佳答案

JLS rule for field access ambiguity

If the identifier names several accessible (§6.6) member fields in type T, then the field access is ambiguous and a compile-time error occurs.

on the subject of accessibility

A member (class, interface, field, or method) of a reference type, or a constructor of a class type, is accessible only if the type is accessible and the member or constructor is declared to permit access:

它不区分实例字段访问是否会在 static 上下文中导致编译错误。

注意你本来可以

public static void main(String args[]) {
Test test = new Test();
System.out.println("var:" + test.var);
}

你仍然会有歧义。

关于java - Java 中来自静态上下文的模糊调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24612590/

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