Search code examples
javaabstract-class

Accessing sub class static attributes from superclass method


I will give a quick example since is not that complicated when viewed in that way. The output below example will be null:

abstract class SuperClass { // it doesn't need to be abstract but that's my case now
    // needs to be static
    static String var_name = null;
    void method(){
        System.out.println(var_name);
    }
}
class subclass{
    // needs to be static
    static String var_name = "I need to print this"
    void otherUnrelatedMethod(){
        method(); // calling method() here gives me null
    }
}

I'm aware of two options to achieve what I want:

I can easily achieve this just by passing var_name as a parameter on method(), which is the option I'm using right now.

Also I can override method(), but doing that would bring a lot more work since there is a lot of subclasses and method() is actually pretty big.

Is there any other option besides these two? I.e.: If I could maybe use bounding with a subclass type <S extends SuperClass> to get de desirable effect. Or even using reflection, although I heard it can make the program quite slow


Solution

  • Here is a nice pattern for this kind of problem:

    abstract class SuperClass { 
        String var_name() {
            return null;
        }
    
        void method() {
            System.out.println(this.var_name());
        }
    }
    
    class subclass extends SuperClass {
        @Override
        String var_name() {
            return "I need to print this";
        }
    
        void otherUnrelatedMethod() {
            method(); 
        }
    }
    
    
    • First, super class has no information about sub classes. This means that you cannot call sub class function from super class.
    • Second, static members exist in class, not in instance. It is impossible but if one sub class overrides any super class static member, other sub classes will be victims.

    You would better use function that returns var_name and @Override it from sub classes.