enum Enum1
{
BIG(8), HUGE(10)
{
public String getName()
{
return "Huge";
}
public String getContry()
{
return "India";
}//additional Method
},
OVERWHELMING(16)
{
public String getName()
{
return "OVERWHELMING";
}
};
private int ounces;
public int getOunes()
{
return ounces;
}
public String getName()
{
return "Ponds";
}
Enum1(int ounces1)
{
ounces = ounces1;
}
}
class EnumAsInnerClass
{
Enum1 enumInnerClass;
public static void main(String[] args)
{
EnumAsInnerClass big = new EnumAsInnerClass();
big.enumInnerClass = Enum1.BIG;
EnumAsInnerClass over = new EnumAsInnerClass();
over.enumInnerClass = Enum1.OVERWHELMING;
EnumAsInnerClass huge = new EnumAsInnerClass();
huge.enumInnerClass = Enum1.HUGE;
System.out.println(big.enumInnerClass.getName());//Ponds
System.out.println(over.enumInnerClass.getName());//OVERWHELMING
System.out.println(huge.enumInnerClass.getName());//Huge
}
}
Consider the above example. How can I call the method getCountry for HUGE?
If there is no way to call this method, why does Java treat it as legal?
You can use extension methods to add functionality specific to a particular enum type.
The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
Enums are very powerful as they may have instance variables, instance methods, and constructors. Each enum constant should be written in capital letters. Every enum constant is by default internally public static final of type Enum declared.
An enum class can include methods and fields just like regular classes. When we create an enum class, the compiler will create instances (objects) of each enum constants. Also, all enum constant is always public static final by default.
(As noted nearly 4 years later, my original answer was incorrect.)
You can't even call Enum1.HUGE.getCountry()
with the specific enum, which is very slightly surprising... but even if you could, you couldn't do so with an arbitrary Enum1
value, which would be more generally useful.
The solution is to stop it from being an additional method - add a getCountry()
method into Enum1
, either returning a default value or maybe throwing an exception. HUGE
can then override the method.
It would be nice if you could declare that a particular enum value implemented an interface, but it seems there's no syntax for that.
The enum
is a type definition, similar to a class, so Enum1
doesn't have the method getCountry()
available in its interface.
edit: Alternative solution
What you can do is define the required methods in Enum1
and override them in the individual enum values.
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