-1
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 ?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
lakhansoren
  • 162
  • 1
  • 1
  • 9

1 Answers1

2

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.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
  • Defining the method on the enum level is mandatory. I called Number.One.getDigit() without defining it on the enum level and it throws this error: cannot find symbol System.out.println(Numbers.One.getDigit()); – lakhansoren Aug 29 '16 at 11:46
  • @sorenl You're right. I've updated my answer. – Erwin Bolwidt Aug 29 '16 at 13:54
  • Any reason why java doesn't warn or throw error on declaring public methods inside enum instances when the same method is not exposed by redeclaring in the parent enum? Seems the `getDigit` method is pretty useless if it is not redeclared again in the parent enum and it can be validated at compile time itself. – muthuraj Aug 31 '21 at 14:45