Soujanya
Soujanya

Reputation: 59

How to instantiate an inner class in Enum?

I am wondering how to instantiate an inner class in enum...if i have a code something like this:

public enum TestEnum {
    BIG(1),SMALL(2),LARGE(3);
    int i;

    private TestEnum(int i){
        this.i = i;
    }

    public class cs{
        cs c = new cs(){
            public void met(){
                System.out.println("met in enum inner class");
            }
        };
    }

    public static void main(String[] args){
        //instantiate an object of cs here
    }
}

Is it possible to instantiate?

Upvotes: 0

Views: 448

Answers (3)

Eugene
Eugene

Reputation: 121068

You need an instance of the outer class (enum) in order to create the inner.

tutorial

  TestEnum big = TestEnum.BIG;
        big.new cs();

Upvotes: 0

hoaz
hoaz

Reputation: 10171

This will work:

TestEnum.BIG.new cs();

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

Since the inner class of the enum is non-static, you need an object reference to create new instances of cs:

TestEnum.cs sample = TestEnum.BIG.new cs();
//                            ^^^
// This could be any instance of TestEnum

Note that you could make cs a static nested class if cs does not use its "owner" enum.

Upvotes: 1

Related Questions