sorenl sorenl - 3 months ago 8
Java Question

What is wrong with using enums this way in Java?

public enum Numbers{
One {
public String getDigit(){
return "1";
}
}
,

Two {
public String getDigit(){
return "2";
}
}
,
Three {
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 is the reason for this error? And what is the correct usage for calling declaring methods inside enum for each constants ?

Answer

You have only defined the method getDigit() on the enum constants One, Two and Three, but not on the enum Numbers itself.

If you want to do xyz.getNumbers() as in your main method, then you need to have the method in the enum class itself too. You can leave it abstract.

Define it there as well:

public enum Numbers{
    One {
        @Override
        public String getDigit(){
            return "1";
        }
    },
    Two {
        @Override
        public String getDigit(){
            return "2";
        }
    },
    Three {
        @Override
        public String getDigit(){
            return "3";
        }
    };

    // Define the `getDigit()` method on the level of the enum itself too!
    public abstract String getDigit();
};

Of course in your very simple example it's better to implement it completely 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 your logic is complex then you may override the method on the enum instances themselves.