Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending enum in Java

public enum myEnum {    
VAL1(10), VAL2(20), VAL3("hai") {
        public Object getValue() {
            return this.strVal;
        }
        public String showMsg() {
            return "This is your msg!";
        }
    };
    String strVal;
    Integer intVal;
    public Object getValue() {
        return this.intVal;
    }
    private myEnum(int i) {
        this.intVal = new Integer(i);
    }
    private myEnum(String str) {
        this.strVal = str;
    }
}

In the above enum what exactly happens when I add a constant specific class body for VAL3?

The type of VAL3 is definetly a subtype of myEnum as it has overloaded and additional methods. (the class type comes as 'myEnum$1' )

But how can the compiler creates a subtype enum extending myEnum as all the enums are already extending java.lang.enum ?

like image 909
Saravanan M Avatar asked Dec 17 '25 16:12

Saravanan M


1 Answers

Your class myEnum inherits from java.lang.Enum. VAL3 is an anonymous inner class that inherits from myEnum called myEnum$1. Think of the enum keyword as syntatic sugar. It sets up classes with normal inheritance trees for you, but will not allow you to extend java.lang.Enum or myEnum directly.

like image 160
Craig P. Motlin Avatar answered Dec 20 '25 08:12

Craig P. Motlin



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!