Java: access to the constants in an enumeration (enum)

后端 未结 3 904
北恋
北恋 2020-12-17 20:53

reading the SCJP book, I\'ve found something like this in the chapter 1 \"self-test\" :

enum Animals {
    DOG(\"woof\"), CAT(\"meow\"), FISH(\"burble\");
           


        
相关标签:
3条回答
  • 2020-12-17 21:08

    Writing a.DOG is the same as writing Animal.DOG. That is, the compiler will replace the variable with its compile time type Animal. It is considered bad code since it hides the fact that it relies on the compile time type instead of the dynamic type of a.

    0 讨论(0)
  • 2020-12-17 21:19

    Although this works, don't do it like that. Use enums with Animal.DOG, Animal.CAT, etc.

    What the above does is declare an object of the enum type, and reference the static DOG on it. The compiler knows the type of a, and knows that you want Animal.DOG. But this kills readability.

    I believe the purpose of this is to shorten the usage of enums. a.DOG instead of Animal.DOG. If you really want to shorten it, you can use import static fqn.of.Animal and then use simply DOG.

    0 讨论(0)
  • 2020-12-17 21:29

    You can access statics from an instance, but it's really bad taste as statics aren't as much bound to an instance as bound to the class.

    Whatever the book says, don't use statics that way. And if you run checkstyle and the like, they warn about it too :)

    BTW a is null in your example. Does it get initialized somewhere?

    EDIT

    I know the compiler knows what a.DOG is bound to, as statics can't be overridden. It does not need a to determine the call, only the compile-time type of a, which it has.

    I also know that the example works even though a is null (I tried so I know:).

    But I still think it's weird you can get stuff from null. And it's confusing:

    Animals a = null;
    System.out.println(a.DOG); // OK
    a.doSomething(); // NullPointerException
    

    When I would be debugging the NPE I would assume that a can't be null as the println worked fine. Confusing.

    Ah well, Java. If you think you've seen it all you get something else again :)

    0 讨论(0)
提交回复
热议问题