Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum private method in item's 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 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?

like image 552
Sam YC Avatar asked Dec 16 '22 16:12

Sam YC


2 Answers

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.

like image 173
NPE Avatar answered Jan 01 '23 06:01

NPE


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.

like image 26
Narendra Pathai Avatar answered Jan 01 '23 05:01

Narendra Pathai