user7796543
user7796543

Reputation:

Select appropriate enum class based on class member

I have an absract class that describes a general functionality of children classes. When I initialize a child class I want to set a specific enum class as a member on the parent abstract class. How can I do that?

Example: 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");
    }
}

How can I specify that I want the public enum Writers in my Child1 class?

Upvotes: 3

Views: 234

Answers (2)

dreamcrash
dreamcrash

Reputation: 51423

The simpler approach is just add the enum type as the type of the field parameter of the abstract 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;
    }
}

the subclass:

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

Alternatively, you can make your enum Writers implement a more general interface let us say 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;
    }
}

The interface:

public interface IWriters {
     ... 
}

the enum:

public enum Writers implements IWriters{
    ...
}

The benefit of this approach is that you can have different enums types implementing the same interface, and therefore they can also be used on the abstract class.

Upvotes: 1

mfe
mfe

Reputation: 1208

Maybe you can set generic in abstract 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;
    }

In the sub class

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

Upvotes: 0

Related Questions