How would you implement multiple inheritance in Java?

Multiple inheritance is the ability of a single class to inherit from multiple classes. Java does not have this capability.

The designers of Java considered multiple inheritance to be too complex, and not in line with the goal of keeping Java simple.

Multiple inheritance can cause the diamond problem

One specific problem that Java avoids by not having multiple inheritance is called the diamond problem. You can read more about that problem here: Java diamond problem.

Java’s alternative to multiple inheritance – interfaces

What a Java class does have is the ability to implement multiple interfaces – which is considered a reasonable substitute for multiple inheritance, but without the added complexity. This is what a Java class that implements multiple interfaces would look like:

// Wolf and Canine are interfaces

public class Dog implements Wolf, Canine {

You can also have a class that extends one class, while implementing an interface – or even multiple interfaces. So, a class like this is perfectly legal in Java:

// Wolf is an interface
// Dog is a base class

// Poodle both extends from a class and implements
// an interface
public class Poodle extends Dog implements Wolf {

So, remember that although Java does not have multiple inheritance, a Java class does have the ability to implement multiple interfaces instead.

C++ does support multiple inheritance

However, C++ does support multiple inheritance. Syntactically, multiple inheritance in C++ would look like this, where class X derives from 3 classes – A, B, and C:

class X : public A, private B, public C { /* ... */ };

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.