Why can't a class extend an enum?

后端 未结 5 1829
死守一世寂寞
死守一世寂寞 2021-01-17 10:18

I am wondering why in the Java language a class cannot extend an enum.

I\'m not talking about an enum extending an enum<

5条回答
  •  天涯浪人
    2021-01-17 11:03

    In ancient days of pre Java 1.5 you would probably do enums like this:

    public class MyEnum {
    
    public static final MyEnum ASD = new MyEnum(5);
    public static final MyEnum QWE = new MyEnum(3);
    public static final MyEnum ZXC = new MyEnum(7);
    
    private int number;
    
    private MyEnum(int number) {
        this.number = number;
    }
    
    public int myMethod() {
        return this.number;
        }
    
    } 
    

    There are two important things about this figure:

    • private constructor that will not allow to instantiate the class from outside
    • actual "enum" values are stored in static fields

    Even if it's not final when you'll extend it, you'll realize that compiler requires an explicit constructor, that in other turn is required to call super constructor which is impossible since that one is private. Another problem is that the static fields in super class still store object of that super class not your extending one. I think that this could be an explanation.

提交回复
热议问题