Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using inner classes in Java - enum

I have a very specific issue that has to do with an inner class. Let me show you some sample code:

class Foo {
    MYOPTIONS temp;

    public static enum MYOPTIONS {
        OPTION1, OPTION2, OPTION3;
    } 
}

So this enumeration is inside the class Foo. Now what I want to do is set the temp variable as one of the three options, but do that outside the class Foo, let's say from a class called External. Unfortunately I cannot have a set method to do that because External.setTemp (MYOPTIONS.OPTION1) is not valid, as the enum is not visible in class external. So the only thing I could come up with is have three methods in class Foo:

public void setTempOption1 () {this.temp=MYOPTIONS.OPTION1;}
public void setTempOption2 () {this.temp=MYOPTIONS.OPTION2;}
public void setTempOption3 () {this.temp=MYOPTIONS.OPTION3;}

Obviously the other option is to change the enumeration and not have it as an inner class. Are there any other options that I am missing? Thanks

like image 441
sakis kaliakoudas Avatar asked Apr 28 '12 10:04

sakis kaliakoudas


People also ask

Can enum be an inner class in Java?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can we declare enum inside class?

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

What is nested enum in Java?

Department enum defined above is a nested enum type as it is 'nested' inside another class. Nested enum types are implicitly static, and hence mentioning static in their definition is actually redundant. An enum constant of static nested enum Department type can be accessed using the syntax – <enclosing-class-name>.

Can enums be defined inside interface?

Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version.


2 Answers

class ContainsInnerEnum {
    MYOPTIONS temp;

    public enum MYOPTIONS {
        OPTION1, OPTION2, OPTION3;
    } 
}

class EnumTester {
    public void test () {
        ContainsInnerEnum ie = new ContainsInnerEnum ();
        // fail:
        // ie.temp = MYOPTIONS.OPTION1;
        // works:
        ie.temp = ContainsInnerEnum.MYOPTIONS.OPTION1;
    }       
}

The whole name of the MYOPTIONS contains the embedding class name.

like image 143
user unknown Avatar answered Oct 05 '22 02:10

user unknown


The declaration is valid, but you have to use it in this way:

Foo.MYOPTIONS var = Foo.MYOPTIONS.OPTION1

You are missing the name of the class when you are using the "enum".

like image 41
Ignux02 Avatar answered Oct 05 '22 02:10

Ignux02