Java通用枚举

Mem*_*eak 2 java enums

对于我在Swing中的图标我有不同的枚举,如:

    public enum Icon32 {
    STOP("resources/icons/x32/stop.ico"),
    RUN("resources/icons/x32/run.ico");
    private File path;

    private Icon32(String path) {
        this.path = new File(path);
    }

    public File getFile() {
        return path;
    }
Run Code Online (Sandbox Code Playgroud)

要么

public enum Tab {
    XML("resources/icons/x32/tab/tab_1.ico"), QR("resources/icons/x32/tab/tab_2.ico"),ABOUT("resources/icons/x32/tab/tab_3.ico");
    private File path;

    private Tab(String path) {
        this.path = new File(path);
    }

    public File getFile() {
        return path;
    }

}
Run Code Online (Sandbox Code Playgroud)

我创建了一个抽象实现:

public abstract class AbstractImageType {

private File path;

private AbstractImageType(String path) {
    this.path = new File(path);
}

public File getFile() {
    return path;
}

@Override
public String toString() {
    return path.toString();
}
Run Code Online (Sandbox Code Playgroud)

}

但Enum无法扩展:

Syntax error on token "extends", implements expected
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,是否可以创建一个通用类"AbstractImageType"来实现方法和构造函数?所以我只想插入枚举值?

像这样的东西:

 public enum Icon32 extends AbstractImageType {
    STOP("resources/icons/x32/stop.ico"),
    RUN("resources/icons/x32/run.ico");
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*exR 6

java中的枚举不支持类的继承,因为每个枚举enum实际上都是一个扩展的简单类Enum.由于不支持多重继承,因此无法为2个枚举创建基类.

您可以停止使用枚举为了这个目的,即切换到普通班或使用委派创建文件,即接受枚举成员,并返回程序File实例.


Adr*_*onk 5

您可以创建AbstractImageType一个界面并让您的枚举实现它.

public interface AbstractImageType {

    File getFile();
}

public enum Icon32 implements AbstractImageType  {
    STOP("resources/icons/x32/stop.ico"),
    RUN("resources/icons/x32/run.ico");
    private File path;

    private Icon32(String path) {
        this.path = new File(path);
    }

    public File getFile() {
        return path;
    }
}
Run Code Online (Sandbox Code Playgroud)