Java does not support multiple inheritance through classes, but it allows a class to implement multiple interfaces. This enables a class to inherit multiple sets of behaviors or capabilities without the ambiguity problems associated with multiple class inheritance.
Key Points: • A Java class can implement multiple interfaces simultaneously. • This provides the benefits of multiple inheritance without the Diamond Problem. • Interfaces define contracts, and the implementing class provides the actual implementation. • Multiple interfaces promote flexibility, loose coupling, and code reusability. • If multiple interfaces contain the same default method, the implementing class must override it to resolve the conflict.
Example: A SmartPhone can perform multiple roles. It can make calls and take photos. These capabilities can be defined through separate interfaces and implemented by a single class.
Code Example:
interface Camera {
void takePhoto();
}
interface Phone {
void makeCall();
}
class SmartPhone implements Camera, Phone {
@Override
public void takePhoto() {
System.out.println("Taking Photo");
}
@Override
public void makeCall() {
System.out.println("Making Call");
}
}
public class Demo {
public static void main(String[] args) {
SmartPhone phone = new SmartPhone();
phone.takePhoto();
phone.makeCall();
}
}Output:
Taking Photo Making Call
Real-World Example:
A Smart TV can: • Display video content • Connect to Wi-Fi • Support voice commands
Instead of inheriting from multiple classes, it can implement multiple interfaces such as Displayable, Connectable, and VoiceControlled.
Benefits of Using Multiple Interfaces:
• Avoids ambiguity issues • Supports multiple inheritance of type • Promotes loose coupling • Improves maintainability • Increases flexibility and scalability
Interview Tip: A concise interview answer is:
"Java does not support multiple inheritance through classes, but a class can implement multiple interfaces. This allows the class to inherit multiple behaviors while avoiding ambiguity problems such as the Diamond Problem. For example, a SmartPhone can implement both Camera and Phone interfaces."