Skip to content
Advertisement

(Java) Static member accessed via instance reference with enumerators

I just started learning Java. IntelliJ is giving me a warning “Static member accessed via instance reference” on line 4. Is it bad, should I fix it, somehow, or should I just ignore it?

Here is my code:

JavaScript

and the Dog class:

JavaScript

Advertisement

Answer

One issue (which causes others) is that you’re hiding the type breed by also having a field of the same name in the same scope.

That’s a very rare problem to have, because the naming conventions of Java usually prevent this kind of clash: Types (classes, interfaces, enums, annotations) are usually written in CamelCase whereas field names start with a lower case letter (fieldName). While this is not technically a “rule” that the compiler enforces, following this makes your code much more readable to others and also avoids the follow-up problem of hiding the type. Also note that constant fields.

I also made two changes that are good ideas but not really related to your issue:

  • constant values (i.e. most static final fields an enum constants) use ALL_UPPER casing, so I also changed your Breed values
  • I’ve moved the nested type definition to the top of your Dog class so as not to hide it within all the instance fields. This is just to keep those things that logically belong together close to each other.
JavaScript

Changing all these names in the main class and replacing the unneded new Dow().breed with just Dog.Breed produces this working code:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement