Can I extend a class and override enclosed enum type?

前端 未结 3 970
生来不讨喜
生来不讨喜 2021-02-05 12:43

If I have a class that contains an enum type, can I extend this class and override the enum type or add more constants to this enum? The purpose is that user will b

3条回答
  •  一整个雨季
    2021-02-05 13:20

    You can't extend enum. enums are essentially a final class. However, enums can implement, so combined with generics, you get:

    interface Color{
    
    }
    enum CarColor implements Color{
        BLUE,
        GREEN;
    }
    enum RacingCarColor implements Color{
        BLUE,
        GREEN,
        YELLOW;
    }
    class Vehicle {
        protected T color;
        protected Vehicle(T color){
            this.color = color;
        }
        public T getColor(){
            return color;
        }
    }
    
    class Car extends Vehicle{ 
        public Car(CarColor color){
            super(color);
        }
    }
    
    class RacingCar extends Vehicle{ 
        public RacingCar(RacingCarColor color){
            super(color);
        }
    }
    

    Voila!


    If you want to require that the type be a Color and be an enum, use this bound:

    class Vehicle & Color> { ...
    

    Or a curious equivalent:

    class Vehicle> { ...
    

提交回复
热议问题