Java – how do you call other methods in an enumeration?
•
Java
enum Enum1
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 example above How to call the method getcountry for huge?
If this method cannot be called, why does Java consider it legal?
Solution
(as I said about four years later, my original answer was wrong.)
You can't even call enum1 with a specific enumeration HUGE. Getcountry(), which is very surprising... But even if you can, you can't use any enum1 value, which is usually useful
The solution is to prevent it from becoming an additional method - add a getcountry () method in enum1, return the default value or throw an exception Huge can then override the method
It would be nice if you could declare that a specific enumeration value implements an interface, but it seems to have no syntax
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码