Saravanan M
Saravanan M

Reputation: 4747

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 ?

Upvotes: 3

Views: 8553

Answers (2)

geeeeeeeeeek
geeeeeeeeeek

Reputation:

From decompiler


package com.sun.tools.xjc.outline;


public final class Aspect extends Enum
{
    public static final Aspect EXPOSED;
    public static final Aspect IMPLEMENTATION;
    private static final Aspect $VALUES[];

    static 
    {
        EXPOSED = new Aspect("EXPOSED", 0);
        IMPLEMENTATION = new Aspect("IMPLEMENTATION", 1);
        $VALUES = (new Aspect[] {
            EXPOSED, IMPLEMENTATION
        });
    }

    public static final Aspect[] values()
    {
        return (Aspect[])$VALUES.clone();
    }

    public static Aspect valueOf(String name)
    {
        Aspect arr$[] = $VALUES;
        int len$ = arr$.length;
        for(int i$ = 0; i$ < len$; i$++)
        {
            Aspect aspect = arr$[i$];
            if(aspect.name().equals(name))
                return aspect;
        }

        throw new IllegalArgumentException(name);
    }

    private Aspect(String s, int i)
    {
        super(s, i);
    }


}

Upvotes: 0

Craig P. Motlin
Craig P. Motlin

Reputation: 26740

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.

Upvotes: 5

Related Questions