Jul 22
Protected within Java Enums
I just noticed that java enums allow protected member variables and methods. Why is this interesting? Can you think of any code that might actually make use of a protected member in an enum (as opposed to private)? Example after the jump (warning, not practical…).
package enumerations; public enum ExampleEnum{ FIRST{ protected int getNumber(){ return 3; } },SECOND, THIRD; public void printNumber(){ System.out.println(getNumber()); } protected int getNumber(){ return -1; } public static void main(String []args){ FIRST.printNumber(); SECOND.printNumber(); THIRD.printNumber(); } }
This will print out
3 -1 -1
The enumeration-specific implementation is basically a subclass of the enumeration itself and can override protected methods. I’m finding it hard to think of a practical reason to do this, but still:)
No commentsNo Comments
Leave a comment