java - 为什么Java中的final常量可以被重写?

标签 java interface overriding final

考虑 Java 中的以下接口(interface):

public interface I {
    public final String KEY = "a";
}

还有下面的类:

public class A implements I {
    public String KEY = "b";

    public String getKey() {
        return KEY;
    }
}

为什么类 A 可以覆盖接口(interface) I 的最终常量?

亲自尝试一下:

A a = new A();
String s = a.getKey(); // returns "b"!!!

最佳答案

你把它隐藏了,这是“Scope”的一个功能。任何时候你在一个较小的范围内,你都可以重新定义你喜欢的所有变量,并且外部范围变量将被“隐藏”

顺便说一句,如果您愿意,您可以再次确定范围:

public class A implements I {
    public String KEY = "b";

    public String getKey() {
        String KEY = "c";
        return KEY;
    }
}

现在 KEY 将返回“c”;

编辑是因为重读时原著很糟糕。

关于java - 为什么Java中的final常量可以被重写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/205239/

相关文章:

java - Vaadin: "Ids must exist in the Container",在调用 setVisibleColumns() 之后

java - 如何修复 "if"始终变为 "true"

c# - 检索类型的叶接口(interface)

javascript - 自定义警报的返回值

ios - 如何在 if else 语句中插入覆盖函数

java - 每天更新随机字符串

java - 使用计算机名称而不是 IP 地址通过 Wi-Fi 连接

c# - 在 C# 中,有没有办法让类使用接口(interface)或抽象类定义字段?

c# - 如何设置显式实现的接口(interface)的属性?

jQuery 覆盖 $.post 函数