java—根据类成员选择适当的枚举类

kkbh8khc  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(361)

我有一个abstract类,它描述了children类的一般功能。当我初始化一个子类时,我想将一个特定的枚举类设置为父抽象类的成员。我该怎么做?
示例: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;
    }
}

儿童1.java

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

如何指定我想要 public enum Writers 在我的 Child1 上课?

6yjfywim

6yjfywim1#

更简单的方法是添加 enum 类型作为抽象类的字段参数的类型:

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;
    }
}

子类:

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{
...
}

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

gopyfrb32#

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

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;
    }

在子类中

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

相关问题