简体   繁体   English

从超类方法访问子类静态属性

[英]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.只需将 var_name 作为 method() 的参数传递,我就可以轻松实现这一点,这是我现在正在使用的选项。

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.我也可以覆盖method(),但是这样做会带来更多的工作,因为有很多子类并且method()实际上非常大。

Is there any other option besides these two?除了这两个,还有别的选择吗? Ie: If I could maybe specify inside method() the variable from "something that extends SuperClass"?即:如果我可以在 method() 中指定来自“扩展 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.其次, static成员存在于class ,而不存在于 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.您最好使用从子类返回var_name@Override函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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