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

后端 未结 3 903
北恋
北恋 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: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 :)

提交回复
热议问题