Why can final constants in Java be overridden?

后端 未结 6 1476
暗喜
暗喜 2020-12-28 14:25

Consider the following interface in Java:

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

And the following class:



        
6条回答
  •  悲哀的现实
    2020-12-28 14:41

    You are hiding it, it's a feature of "Scope". Any time you are in a smaller scope, you can redefine all the variables you like and the outer scope variables will be "Shadowed"

    By the way, you can scope it again if you like:

    public class A implements I {
        public String KEY = "b";
    
        public String getKey() {
            String KEY = "c";
            return KEY;
        }
    }
    

    Now KEY will return "c";

    Edited because the original sucked upon re-reading.

提交回复
热议问题