Why can final constants in Java be overridden?

后端 未结 6 1484
暗喜
暗喜 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:56

    As a design consideration,

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

    The static methods always returns the parent key.

    public class A implements I {
        public String KEY = "b";
    
        public String getKey() {
            return KEY; // returns "b"
        }
    
        public static String getParentKey(){
            return KEY; // returns "a"
        }
    }
    

    Just like Jom has noticed. The design of static methods using re-defined interface members could be a heavy problem. In general, try to avoid use the same name for the constant.

提交回复
热议问题