Mahesha Padyana
Mahesha Padyana

Reputation: 431

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. 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? 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(). Inside this method, I need to use the variables var1, values and many other variables of subclasses. 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? 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.

Upvotes: 1

Views: 1053

Answers (1)

folkol
folkol

Reputation: 4883

Add a getter method and override it in either subclass.

public int getVar() {
    return var1;
}

Upvotes: 1

Related Questions