java - 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 on = 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 above example. how can call method getcountry huge?

if there no way call method, why java treat legal?

(as noted 4 years later, original answer incorrect.)

you can't call enum1.huge.getcountry() specific enum, surprising... if could, couldn't arbitrary enum1 value, more useful.

the solution stop being additional method - add getcountry() method enum1, either returning default value or maybe throwing exception. huge can override method.

it nice if declare particular enum value implemented interface, seems there's no syntax that.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -