There is actually a good reason:
Non-static access does not always work due to ambiguity .
Suppose we have two classes: A and B, the latter being a subclass of A, with static fields with the same name:
public class A { public static String VALUE = "Aaa"; } public class B extends A { public static String VALUE = "Bbb"; }
Direct access to a static variable:
A.VALUE (="Aaa") B.VALUE (="Bbb")
Indirect access using an instance (gives a warning to the compiler that VALUE should be statically accessed):
new B().VALUE (="Bbb")
So far, so good, the compiler can guess which static variable to use, something that is somehow far away in the superclass seems logical.
Now that is getting complicated: interfaces can also have static variables.
public interface C { public static String VALUE = "Ccc"; } public interface D { public static String VALUE = "Ddd"; }
Let me remove the static variable from B and observe the following situations:
B implements C, DB extends A implements CB extends A implements C, DB extends A implements C where A implements DB extends A implements C where C extends D- ...
The statement new B().VALUE now ambiguous , since the compiler cannot decide which static variable had in mind , and will report this as an error:
error: link to VALUE is ambiguous
the VALUE variable in C and the VALUE variable in D correspond
And for this very reason, static variables must be available in a static way.
Peter Walser Aug 25 '14 at 21:25 2014-08-25 21:25
source share