Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling method on enum

Tags:

java

enums

public enum AgeGroup {
        CHILD{
           public int get(){
               return 10;
           } 
        }, 
        TEEN, YOUNG, MID, OLD;
    }

I have an enum AgeGroup and as you are seeing that CHILD has one method get(). Can somebody tell me why we can't call get() from CHILD what is the design approach behind this or why is it designed like this?

like image 979
Trying Avatar asked Jul 22 '26 18:07

Trying


1 Answers

Firstly, all instances of an enum are of the same type, which means all instances have the same set of methods.

You need to declare a method on the enum type itself for instances to have a method:

public enum AgeGroup {
    CHILD{
       public int get(){
           return 10;
       } 
    }, 
    TEEN, YOUNG, MID, OLD;
    public int get() {
        return 0;
    }
}

If all instances overrode the get() method as CHILD has, you could declare the method as abstract, which forces the coder to implement the method if new instances are added.

The best approach is to use a final field, initialized via a custom constructor, with a getter:

public enum AgeGroup {
    CHILD{10), TEEN(19), YOUNG(35), MID(50), OLD(80);
    private final int age;
    AgeGroup(int age) {
        this.age = age;
    }
    public int get() {
        return 
    }
}
like image 135
Bohemian Avatar answered Jul 25 '26 08:07

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!