Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Parent call Child Class methods?

Tags:

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:

  • I don't want to touch A(only as a last option though that is if no other solution exists).
  • I don't want to use reflection.

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

like image 851
Kevin Boyd Avatar asked Sep 07 '09 01:09

Kevin Boyd


People also ask

Can parent reference call child method in Java?

yes it is possible to hold child object with parent reference.. it is also a polymorphism and we generally use this approach when we are not sure about the run time object type.

Can a parent class access child class in Java?

The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.


2 Answers

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".

like image 54
Alex Martelli Avatar answered Nov 07 '22 23:11

Alex Martelli


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.

like image 39
Timmmm Avatar answered Nov 07 '22 21:11

Timmmm