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
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.
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>.
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.
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.
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".
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