How to Implement Multiple Inheritance in Java

Java do not support direct multiple inheritance, we need to use interfaces to achieve it. Lets assume, we have two robots Walker and Flyer. Walker only walk, and Flyer can only Fly.

[java]public interface Walker{
public walk();
}
public interface Flyer{
public fly();
}[/java]
Say, the company has created another robot, lets call it AllRounder, which can walk, fly, swim and run. We have already Walker and Flyer, so how we can use earlier written code using inheritance. This is how it goes ...
[java]public class AllRounder implements Walker, Flyer {
public walk() {
// write code, how AllRounder walk
}
public fly() {
// write code, how AllRounder fly
}
public run() {
// write code, how AllRounder run
}
public swim() {
// write code, how AllRounder swim
}
} // end of class
[/java]
The wise question is, what if AllRounder walk and fly in the same way our earlier robots do. Then we should not redefine walk and fly behavior in AllRounder class but use earlier written implementation. We can achieve it like this. Say we have Walker and Flyer implementations like this:
[java]public class WalkerImpl implements Walker {
public walk() {
// write code, how Walker walks
}
}
public class FlyerImpl implements Flyer {
public fly() {
// write code, how Flyer fly
}
} [/java]
What we want to do is, when a client call allRounder.fly(), the above fly() method should be invoked. To achieve this, we need to update AllRounder class a bit. The updated copy will look like this.
[java]public class AllRounder implements Walker, Flyer {
private Walker walker;
private Flyer flyer;
public AllRounder() {
this.walker = new WalkerImpl();
this.flyer = new FlyerImpl();
}
public walk() {
this.walker.walk();
}
public fly() {
this.flyer.fly();
}
public run() {
// write code, how AllRounder run
}
public swim() {
// write code, how AllRounder swim
}
} // end of class
[/java]
Of course you an remove walk() and fly() implementation from above class, but then you have to call walk() like this, from some client.
[java]AllRounder myGreatRobot = new AllRounder();
myGreatRobot.walker.walk(); [/java]
You see, it looks very bad. And it seems as there is no inheritance working behind. Using above AllRounder implementation, you can call walk(), fly() and other methods like this.
[java]AllRounder myGreatRobot = new AllRounder();
myGreatRobot.walk();
myGreatRobot.run();
myGreatRobot.fly();
myGreatRobot.swim();[/java]
Hope it helped!

Comments