
Originally Posted by
java_learner
I am sure there is an easy way to do it
The easy way is to use dynamic inheritance rather than static.
There's a trick involved. You split the base class into an interface and an implementation class. It goes like this,
Code:
class Base {
public void methodA() {
}
}
The above base class is split into
Code:
interface Base_Interf {
void methodA();
}
class Base_Impl implements Base_Interf {
public void methodA() {
}
}
Now instead of using static inheritance in a derived class like
Code:
class Derivered extends Base {
}
you do,
Code:
class Derivered implements Base_Interf {
private Base_Impl bi = new Base_Impl();
public void methodA() { // implements interface
bi.methodA(); // calls implementation by delegation
}
}
As you can see the derived class now will behave exactly like before from the outside. It's just that it's free to switch implementations inside (which actual implementation is used will be determined by which implementation object the bi variable holds).
You could have a number of Base_Impl classes like Base_Impl_1, Base_Impl_2 etcetera and even switch between them at runtime if you wish.
Or you could have different derived class like Derived_1, Derived_2 etcetera, each using Base_Impl_1 and Base_Impl_2 respectively.
So dynamic inheritance means the derived classes aren't restricted to use the one implementation inherited from the base class only. Instead they're free to use whichever implementation suits their liking. And they can even switch at runtime, thus "dynamic".