简体   繁体   中英

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? Ie: If I could maybe specify inside method() the variable from "something that extends SuperClass"?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM