Java Enum private method in element constructor

public enum Parent { item1(1){ public void testing() { add(); multiply(); minus(); // error here!!! } }, item2(2); private int i ; Parent(int i){ this.i = i; } public void setI(int i ){ this.i = i; } public int getI(){ return i; } public void multiply(){ } protected void add(){ } private void minus(){ } } 

As you guy see, they are in the same class, why minus() cannot be used internally? Usually inner class can access private method/field in outer class?

+4
source share
3 answers

To access minus() from item1 , you must make it protected (or public ).

The right way to think about Parent and item1 is both a base class and a subclass.

From JLS :

The optional body of the enum constant class implicitly defines an anonymous class declaration (Β§15.9.5) , which extends the immediately including enumeration type .

+8
source

Actually, what happens when you provide an implementation when creating an enum object, you basically extend the Parent class with an additional method, i.e. Anonymous . Thus, it does not allow access to the private method of the Parent class, but allows protected and public .

 enum A{ a{ @Override public void method() { // TODO Auto-generated method stub super.method(); } }; public void method(){ } } 

This should explain the explanation of @Override provided by eclipse.

+2
source

The problem is that "item1" is not an internal Parent class, it is really a top-level class. To check if there is a generated class for item1, this is Parent $ 1.class, if it was an inner class, it will be Parent $ item1.class

+1
source

All Articles