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 can see, they are in the same class, how come minus()
cannot be used internally? Usually inner class can access private method/field
in the outer class right?
To be able to access minus()
from item1
, you have to make it protected
(or public
).
The correct way to think about Parent
and item1
is as a base class and a subclass.
From the JLS:
The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type.
Actually what happens is when you provide implementation while creating enum object, you are basically extending the Parent
class with an extra method i.e. Annonymous implementation. So it does not allow to access private method of 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 see the @Override
annotation provided by eclipse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With