Kevin Boyd
Kevin Boyd

Reputation: 12379

Can a Parent call Child Class methods?

Referring here

A is a precompiled Java class (I also have the source file) B is a Java class that I am authoring
B extends A.

How can logic be implemented such that A can call the methods that B has.
The following are the conditions:

As stated, if needed I could modify A. What could be the possible solution either way?

Upvotes: 22

Views: 83302

Answers (3)

Timmmm
Timmmm

Reputation: 96801

Yes it seems that if you override the super/base-classes's functions, calls to those functions in the base class will go to the child/derived class. Seems like a bad design in my opinion, but there you go.

class Base
{
    public void foo()
    {
        doStuff();
    }
    public void doStuff()
    {
        print("base");
    }
}

class Derived extends Base
{
    @Override
    public void doStuff()
    {
        print("derived");
    }
}

new Derived().foo(); // Prints "derived".

Obviously all of Derived's methods have to be already defined in Base, but to do it otherwise (without introspection) would be logically impossible.

Upvotes: 17

user124493
user124493

Reputation:

I would be rather hesitant to do this. Please correct me if I am wrong and then I will delete, but it sounds like you want to maintain an A object along with a B object. If they indeed are not the same object, the "tying together" (that's a scientific term) you'll have to do would be pretty ugly.

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 882103

Class A should define the methods it's going to call (probably as abstract ones, and A should be an abstract class, per Paul Haahr's excellent guide); B can (in fact to be concrete MUST, if the method are abstract) override those methods. Now, calls to those methods from other methods in A, when happening in an instance of class B, go to B's overrides.

The overall design pattern is known as Template Method; the methods to be overridden are often called "hook methods", and the method performing the calls, the "organizing method".

Upvotes: 46

Related Questions