user2762979
user2762979

Reputation: 119

Can a parent class call the method of a grandchild class?

I have a main method in my overall parent class, outside of that main method I have two other methods that I will call inside the main method. Each of these outside methods call a method that was defined in, not the child, but the grandchild class.

Here is where I get really confused. In my big parent class, the two methods that aren't the main method take in an array that is the type of the child class. This is because each item in the array is a different type the grandchild classes. I get that because the methods that I'm calling in the parent class aren't defined in the child class (they are defined in the grandchild class) that is why they cannot be called. Is there a way to typecast the indexes to each individual grandchild class type in a for loop in the array? Or any other way?

Sorry if this is a super confusing way to phrase this question.

Upvotes: 0

Views: 1483

Answers (1)

Kenster
Kenster

Reputation: 25439

The normal way to do this is for the parent class to be declared abstract, and to declare that the method should exist. The grandchild class will supply a version of the method. For example:

public abstract class Doubler {
    int a;

    public Doubler(int a) {
        this.a = a;
    }

    abstract int modifyResult(int aResult);

    int calculate() {
        int rv = a * 2;
        return modifyResult(rv);
    }
}

public class DoublerAndAdder extends Doubler {
    int b;

    public DoublerAndAdder(int a, int b) {
        super(a);
        this.b = b;
    }

    @Override
    public int modifyResult(int aResult) {
        return aResult + b;
    }
}

calculate() is allowed to call modifyResult() even though modifyResult() is declared abstract and there is no implementation. Calling DoublerAndAdder.calculate() will run Doubler.calculate(), which will call DoublerAndAdder.modifyResult().

If you can't make the parent class abstract, the parent class can provide a version of the method which doesn't do anything:

public abstract class Doubler {
    int a;

    public Doubler(int a) {
        this.a = a;
    }

    public int modifyResult(int aResult) {
        return aResult;
    }

    int calculate() {
        int rv = a * 2;
        return modifyResult(rv);
    }
}

Upvotes: 4

Related Questions