Why should the static field be accessed in a static way?

前端 未结 3 657
栀梦
栀梦 2020-11-29 01:17
public enum MyUnits
{
    MILLSECONDS(1, \"milliseconds\"), SECONDS(2, \"seconds\"),MINUTES(3,\"minutes\"), HOURS(4, \"hours\");

    private MyUnits(int quantity, S         


        
3条回答
  •  盖世英雄少女心
    2020-11-29 01:29

    There's actually a good reason:
    The non-static access does not always work, for reasons of 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 the static variable:

    A.VALUE (="Aaa")
    B.VALUE (="Bbb")
    

    Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):

    new B().VALUE (="Bbb")
    

    So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.

    Now to the point where it gets tricky: Interfaces can also have static variables.

    public interface C {
        public static String VALUE = "Ccc";
    }
    
    public interface D {
        public static String VALUE = "Ddd";
    }
    

    Let's remove the static variable from B, and observe following situations:

    • B implements C, D
    • B extends A implements C
    • B extends A implements C, D
    • B extends A implements C where A implements D
    • B extends A implements C where C extends D
    • ...

    The statement new B().VALUE is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:

    error: reference to VALUE is ambiguous
    both variable VALUE in C and variable VALUE in D match

    And that's exactly the reason why static variables should be accessed in a static way.

提交回复
热议问题