How can you achieve Multiple Inheritance in Java?
Java’s interface can be used to implement multiple inheritance, with one important difference from c++ way of doing multiple inheritance: the inherited interfaces must be abstract. This obviates the need to choose between different implementations, as with interfaces there are no implementations.
interface CanFight
{
void fight();
}
interface CanSwim
{
void swim();
}
interface CanFly
{
void fly();
}
class ActionableCharacter
{
public void fight()
{
}
}
class Hero extends ActionableCharacter implements CanFight, CanSwim, CanFly
{
public void swim()
{
}
public void fly()
{
}
}
We can even achieve a form of multiple inheritance where you can use the *functionality* of classes rather than just the interface:
interface A
{
void methodA();
}
class AImpl implements A
{
void methodA() { //do stuff }
}
interface B
{
void methodB();
}
class BImpl implements B
{
void methodB() { //do stuff }
}
class MultipleInheritance implements A, B
{
private A a = new A();
private B b = new B();
void methodA()
{
a.methodA();
}
void methodB()
{
b.methodB();
}
}
This completely solves the traditional problems of multiple inheritance in C++ where name clashes occur between multiple base classes. The coder of the derived class will have to explicitly resolve any clashes. Don’t you hate people who point out minor typos? Everything in the previous example is correct, except you need to instantiate an AImpl and BImpl. So class Multiple would look like this:
class MultipleInheritance implements A, B
{
private A a = new AImpl();
private B b = new BImpl();
void methodA()
{
a.methodA();
}
void methodB()
{
b.methodB();
}
}
Recent Comments