Does Java support Multiple inheritance?

No, Java does not support multiple inheritance in the traditional sense, where a class can inherit from multiple classes. However, Java does provide a limited form of multiple inheritance through interfaces, which allows a class to implement multiple interfaces.

Single Inheritance

In Java, a class can only directly inherit from a single superclass, known as single inheritance. This design choice was made to avoid some of the complexities and ambiguities associated with multiple inheritance, such as the diamond problem, where conflicts can arise when two or more superclasses define the same method or attribute.

Interfaces

Interfaces, on the other hand, can be implemented by classes, and a class can implement multiple interfaces. An interface defines a contract of methods that a class implementing it must provide. By implementing multiple interfaces, a class can inherit and provide behavior from multiple sources.

Following is an example to illustrate the use of interfaces for achieving multiple inheritance-like behavior:

interface Drawable { void draw(); } interface Printable { void print(); } class Shape implements Drawable, Printable { @Override public void draw() { System.out.println("Drawing shape..."); } @Override public void print() { System.out.println("Printing shape..."); } } public class Main { public static void main(String[] args) { Shape shape = new Shape(); shape.draw(); shape.print(); } }

In this example, the interfaces Drawable and Printable define the contract of methods draw() and print() respectively. The class Shape implements both interfaces, allowing it to inherit and provide the behavior specified by the interfaces. The main method demonstrates calling both draw() and print() methods on an instance of Shape, effectively achieving a form of multiple inheritance.

Conclusion

By using interfaces, Java supports achieving some benefits of multiple inheritance, such as code reusability and polymorphism, while avoiding the complexities and conflicts associated with multiple inheritance of implementation details.