Java 枚举类不能直接继承其他类,因为它们是特殊的类,具有唯一性和不可变性。但是,Java 枚举类可以实现一个或多个接口。这样,你可以通过接口实现类似继承的功能,共享方法和属性。
例如,假设你有一个接口 Drawable,它包含一个 draw() 方法:
public interface Drawable {
    void draw();
}
现在,你可以创建一个实现了 Drawable 接口的枚举类 Shape:
public enum Shape implements Drawable {
    CIRCLE {
        @Override
        public void draw() {
            System.out.println("Drawing a circle");
        }
    },
    RECTANGLE {
        @Override
        public void draw() {
            System.out.println("Drawing a rectangle");
        }
    };
    public abstract void draw();
}
这样,Shape 枚举类就继承了 Drawable 接口的方法,并实现了它。现在你可以使用 Shape 枚举类的实例调用 draw() 方法:
public class Main {
    public static void main(String[] args) {
        Shape shape = Shape.CIRCLE;
        shape.draw(); // Output: Drawing a circle
    }
}

 便宜VPS测评
便宜VPS测评










