When one class extends more than one classes then this is called multiple inheritance. For example: Class C extends class A and B then this type of inheritance is known as multiple inheritance. Java doesn’t allow multiple inheritance. In this article, we will discuss why java doesn’t allow multiple inheritance and how we can use interfaces instead of classes to achieve the same purpose.
Why Java doesn’t support multiple inheritance?
C++ , Common lisp and few other languages supports multiple inheritance while java doesn’t support it. Java doesn’t allow multiple inheritance to avoid the ambiguity caused by it. One of the example of such problem is the diamond problem that occurs in multiple inheritance.
What is diamond problem?
We will discuss this problem with the help of the diagram below: which shows multiple inheritance as Class D extends both classes B & C. Now lets assume we have a method in class A
and class B
& C
overrides that method in their own way. Wait!! here the problem comes – Because D is extending both B & C so if D wants to use the same method which method would be called (the overridden method of B or the overridden method of C). Ambiguity. That’s the main reason why Java doesn’t support multiple inheritance.
Can we implement more than one interfaces in a class
Yes, we can implement more than one interfaces in our program because that doesn’t cause any ambiguity(see the explanation below).
interface X { public void myMethod(); } interface Y { public void myMethod(); } class JavaExample implements X, Y { public void myMethod() { System.out.println("Implementing more than one interfaces"); } public static void main(String args[]){ JavaExample obj = new JavaExample(); obj.myMethod(); } }
Output:
Implementing more than one interfaces
As you can see that the class implemented two interfaces. A class can implement any number of interfaces. In this case there is no ambiguity even though both the interfaces are having same method. Why? Because methods in an interface are always abstract by default, which doesn’t let them give their implementation (or method definition ) in interface itself.
No comments:
Post a Comment