Programming Language

How To Implement Multiple Inheritance In Java

Inheritance is the ability of a class to use the methods of another class. Multiple inheritance is defined as the ability of a class to inherit methods from several classes. However, Java does not support multiple inheritance directly. The developers of Java at that time considered the technique to be too complex to implement since it would not keep in line with the goal of keeping Java simple.

What Is The Alternate In Java?

In multiple inheritance, there are several problems that need to be catered. These include ambiguity and name conflicts. However, to avoid these, Java makes use of multiple inheritance by type. The alternative to multiple inheritance in Java therefore is interfaces. A Java Interface is a reference type that is similar to a class. It is a group of abstract methods that can be inherited by other classes. Multiple inheritance can be easily implemented by inheriting multiple interfaces – but without the added complexity. Therefore, through the use of interfaces, we can implement multiple inheritance in Java.

How Is It Implemented?

Suppose that you have two different domains within your program. One is for Trucks that has methods such as Accelerate() and StartEngine(). The other is for Bicycles that has methods such as Pedal() and Stop(). Now there is an energetic young fellow that wants to drive the Bicycle inside the Truck. Now you want to create a Class for Vehicles that implements methods of both the Trucks and Bicycles. In Java, you need to create interfaces for both Trucks and Bicycles with the appropriate methods. The next step is to use the following syntax to implement multiple inheritance:

Class Vehicle extends Truck implements Bicycle

The meaning of this line of code is that the Vehicle Class subclasses a Truck and adds a Bicycle interface to it. This enables us to implement the methods of the Truck and the Bicycle interface within the Vehicle Class. We first have to create an instance of the Bicycle interface within the Vehicle Class and we’re ready to go! This shows how Multiple Inheritance can take be implemented using Java even without the need for inheriting methods from different classes.

Even though Java lacks the option of multiple inheritance (inheriting methods from multiple classes), it has the option of interfaces for providing something with the same functionality. We can effectively implement the methods of several interfaces within a class with the use of multiple inheritance by type.

Leave a Reply