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?
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.
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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With