Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


1 Answers

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.

like image 185
dreamcrash Avatar answered Dec 30 '25 10:12

dreamcrash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!