Core Java Interview Questions and Answers
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:
- How could Java classes direct program messages to the system console, but error messages, say to a file?
- What are the differences between an interface and an abstract class?
- Why would you use a synchronized block vs. synchronized method?
- How can you force garbage collection?
- What are the differences between the methods sleep() and wait()?