Why java supports Multiple Interface Inheritance

Java does not support multiple class inheritance i.e. we cannot extend multiple classes at one time in a class. But we can implememt multiple interfaces in a class. Lets start with the benefits of inheritance.

Interfaces are user for two reasons :-
1) Contract
2) Communication

Contract ,is an aggrement between the interface and the implementing class, that the class will provide the implementation of the methods of the interface's. On has to adhere to the contract. Collections in java has many interfaces like Set, List, Map. These interfaces provide the basic set of methods for the class depending on its interface type.We have their implementation classes like HashSet for Set, ArrayList for List and HashMap for Map.

Communication , is used to communicate certain functionality of a class to the outside world. This is very usefull when you want to expose a class but we dont want that one should know all the methods , variables and other class information. Instead we expose the interface which has some defined methods and one can call those methods only. This technique are highly used in frameworks and remote applications. Lets understand with a example.
        LinkedList class in java implements two interfaces. List and Queue. Each interface has its own set of methods but the use case is differant for each. List is used to store elements as list while queue is based on FIFO or LIFO but the use the same class LinkedList. So, when we wan to use LinkedList as List, we expose as List interface and when we require a LIFO/ FIFO type functionality, we expose the Queue Interface.

Now come to the question i.e. multiple inheritance part. As discussed in Communication part, we can expose a class with a interface. If Java doesnt support multiple inheritance, we have to write different classes for each interface, where each class has the same code, but method names would be different which increase the duplication of code.

Wonderfull, isnt it......!

Comments

Popular posts from this blog

When to use getClass() and instanceOf in Java

How class.forName loads the Database Driver in JDBC

Why Time gets truncated with ResutSet getDate() function.