Select 基于 class 成员的适当枚举 class

Select appropriate enum class based on class member

我有一个摘要 class 描述了 children classes 的一般功能。 当我初始化 child class 时,我想将特定枚举 class 设置为 parent 摘要 class 的成员。 我该怎么做?

示例: AbstractFunctionality.java

public abstract class AbstractFunctionality {
    protected String Name;
    protected String Surname;
    // specific enum class

    public AbstractFunctionality(String Name, String Surname){
         this.Name = Name;
         this.Surname = Surname;
    }
}

Child1.java

public class Child1 extends AbstractFunctionality {
    public Child1(){
        super("Jane","Austen");
    }
}

如何指定我想要 Child1 class 中的 public enum Writers

也许你可以在抽象中设置泛型class

public abstract class AbstractFunctionality<T extends Enum<T>> {
    protected String Name;
    protected String Surname;
    T specificEnum

    public AbstractFunctionality(String Name, String Surname,T specificEnum){
         this.Name = Name;
         this.Surname = Surname;
         this.specificEnum=specificEnum;
    }

在子class

public class Child1 extends AbstractFunctionality<Writers> {
    public Child1(){
        super("Jane","Austen",Writers.POEM);
    }
}
}

更简单的方法是将enum类型添加为摘要字段参数的类型class:

public abstract class AbstractFunctionality {
    protected String Name;
    protected String Surname;
    Writers writers;

    public AbstractFunctionality(String Name, String Surname, Writers writers){
        this.Name = Name;
        this.Surname = Surname;
        this.writers = writers;
    }
}

子class:

public class Child1 extends AbstractFunctionality {
    public Child1(){
        super("Jane","Austen", Writers.SOME_FIELD);
    }
}

或者,您可以让您的枚举 Writers 实现一个更通用的 interface 让我们说 IWriters

public abstract class AbstractFunctionality {
    protected String Name;
    protected String Surname;
    protected IWriters writers;

    public AbstractFunctionality(String Name, String Surname, IWriters writers){
         this.Name = Name;
         this.Surname = Surname;
         this.writers = writers;
    }
}

界面:

public interface IWriters {
     ... 
}

枚举:

public enum Writers implements IWriters{
    ...
}

这种方法的好处是您可以让不同的枚举类型实现相同的接口,因此它们也可以用于抽象 class。