ponds ponds - 6 days ago 8
Java Question

How to call additional method in enums?

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?

Answer

(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.

Comments