简体   繁体   English

如何从超类的方法访问(屏蔽)子类中的成员变量?

[英]How to access (shadowing) member variables in subclass from method in superclass?

Let me know if someone does not understand the question. 让我知道是否有人不明白这个问题。 I tried my best to frame the question below. 我尽力提出以下问题。 I have a common method in parent class for generating pattern. 我在父类中有一个通用方法来生成模式。 For re usability, I thought to retain this method under parent class. 为了提高可用性,我认为应将此方法保留在父类下。

Inside the method, I use several variables. 在方法内部,我使用了几个变量。 So I thought it is better to pass the object as the parameter to the method generatePattern. 因此,我认为最好将对象作为参数传递给generatePattern方法。 But since variables cannot be overridden, how can I use respective variables from these sub classes? 但是由于不能覆盖变量,如何使用这些子类中的各个变量? Any other feature in java other than using subclass? 除了使用子类,Java中还有其他功能吗? Will "Generic types" as parameter work in such case? 在这种情况下,“通用类型”作为参数是否适用?

class Parent {
    int var1;
    String[] values;

    void generatePattern(Parent obj1) {
        // This will not make use of respective values of 
        // subclass object that is passed I guess.
        newPattern(obj1.values, obj1.var1);    
    }
}

class AscendSubClass extends Parent {
    int var1 = 5;
    String[] values = {"S", "R"};
}

class DescendSubClass extends Parent {
    int var1 = 10;
    String[] values = {"N", "D"};
}

I may pass either AscendSubClass or DescendSubClass above to generatePattern(). 我可以将上面的AscendSubClass或DescendSubClass传递给generatePattern()。 Inside this method, I need to use the variables var1, values and many other variables of subclasses. 在此方法内部,我需要使用变量var1,值和子类的许多其他变量。 These variables are of same type and have same name, but the values are different and depends on the subclass. 这些变量具有相同的类型并具有相同的名称,但是值不同并且取决于子类。 How can I refer these variables now in generatePattern() so that method does not change? 我现在如何在generatePattern()中引用这些变量,以使该方法不变? It is possible to achieve this by making variables as a parameters to methods or by if/else statements, but I have several variables to pass and it is big inconvenience. 可以通过将变量作为方法的参数或通过if / else语句来实现此目的,但是我要传递多个变量,这带来了很大的不便。

Add a getter method and override it in either subclass. 添加一个getter方法,并在任一子类中覆盖它。

public int getVar() {
    return var1;
}

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

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