Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Core%20Java%20Interview%20Questions%20and%20Answers

Question: How can you achieve Multiple Inheritance in Java?
Answer:
interface CanFight { 
	void fight(); 
}      

interface CanSwim { 
	void swim(); 
}      

interface CanFly { 
	void fly();
}
       
class ActionCharacter { 
	public void fight() {}
}       

class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { 
	public void swim() {}
	public void fly() {}
}
You 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 Multiple 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 Multiple implements A, B { 
	private A a = new AImpl();
	private B b = new BImpl();
	void methodA() { 
		a.methodA(); 
	}
	void methodB() { 
		b.methodB(); 
	}
}
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook