Why can final constants in Java be overridden?

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

    Static fields and methods are attached to the class/interface declaring them (though interfaces cannot declare static methods as they are wholly abstract classes which need to be implemented).

    So, if you have an interface with a public static (vartype) (varname), that field is attached to that interface.

    If you have a class implement that interface, the compiler trick transforms (this.)varname into InterfaceName.varname. But, if your class redefines varname, a new constant named varname is attached to your class, and the compiler knows to now translate (this.)varname into NewClass.varname. The same applies for methods: if the new class does not re-define the method, (this.)methodName is translated into SuperClass.methodName, otherwise, (this.)methodName is translated into CurrentClass.methodName.

    This is why you will encounter the warning "x field/method should be accessed in a static way". The compiler is telling you that, although it may use the trick, it would prefer that you used ClassName.method/fieldName, because it is more explicit for readability purposes.

提交回复
热议问题