Search code examples
javainheritanceenumsencapsulation

Access to ancestors enums


I have a class A which looks like this:

public abstract class A {

    protected enum Identifier{
        HELLO,WORLD
    }

    private String identifier;

    public void setIdentifier(Identifier identifier){
        this.identifier=identifier.toString();
    }

    public String getIdentifier(){
        return identifier;
    }
}

Now the class hierarchy is this:

B extends A
C extends A
D extends B
E extends D

or A->B->D->E and A->C

Now if I want to use the setter of Identifier enum of A in E how do I go about it. And also I need to use the getter of the same enum in class C. Do I need to create a separate method in each of the sub classes to access the ancestor?


Solution

  • The approach which I took was:

    public abstract class A {
    
        protected enum Identifier{
            HELLO,WORLD
        }
    
        protected Identifier identifier;
    }
    

    In the child class E I am saying identifier = Identifier.HELLO;. I dont know if this is the best approach but even the class C can get the same value of the enum if its part of the same instance. This approach seems to be a bit obfuscate as it is not very clear immediately that where the identifier is inherited from. Any better approach?