syntax - What is wrong with using enums this way in Java? -


this question has answer here:

public enum numbers{     1 {         public string getdigit(){             return "1";         }     }         ,      2 {         public string getdigit(){             return "2";         }     }         ,     3 {         public string getdigit(){             return "3";         }     }  };    public static void main (string[] args) throws java.lang.exception {     numbers xyz = numbers.one;     system.out.println(xyz.getdigit()); } 

above code throws error :

main.java:38: error: cannot find symbol         system.out.println(xyz.getdigit()); 

what reason error? , correct usage calling declaring methods inside enum each constants ?

you have defined method getdigit() on enum constants one, two , three, not on enum numbers itself.

if want xyz.getnumbers() in main method, need have method in enum class too. can leave abstract.

define there well:

public enum numbers{     1 {         @override         public string getdigit(){             return "1";         }     },     2 {         @override         public string getdigit(){             return "2";         }     },     3 {         @override         public string getdigit(){             return "3";         }     };      // define `getdigit()` method on level of enum too!     public abstract string getdigit(); }; 

of course in simple example it's better implement in enum numbers like:

public enum numbers {     one("1"), two("2"), three("3");      private string digit;      numbers(string digit) { this.digit = digit; }      public string getdigit() { return digit; } } 

but if logic complex may override method on enum instances themselves.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -