Why No Multi Class Inherit
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 26 of 87.
Java deliberately prevents a class from extending more than one class. This restriction exists because of a problem known as the Diamond Problem.
Imagine if Java allowed multiple inheritance. Consider this hypothetical scenario:
// This code is NOT valid in Java
public class A {
public void greet() {
System.out.println("Hello from A");
}
}
public class B extends A {
@Override
public void greet() {
System.out.println("Hello from B");
}
}
public class C extends A {
@Override
public void greet() {
System.out.println("Hello from C");
}
}
// NOT allowed in Java!
public class D extends B, C { }If you called greet() on a D object, which version should run? The one from B or C? This ambiguity is the Diamond Problem, named after the diamond shape formed by the inheritance diagram.
Java's solution is simple: allow only single inheritance of classes. However, Java provides an alternative. A class can implement multiple interfaces, which you'll learn about in an upcoming chapter.
Interfaces solve the diamond problem differently and give you flexibility without the ambiguity.
// This IS valid in Java
public class Dog extends Animal implements Runnable, Comparable<Dog> {
// Can implement multiple interfaces
}This design choice keeps Java's inheritance model clean and predictable while still allowing powerful code reuse through interfaces.
Challenge
EasyLet's build a music player system that demonstrates Java's single inheritance rule and shows how you can still achieve flexible designs within this constraint.
Imagine you want to create a smart speaker that combines features from both a music player and a voice assistant. Since Java doesn't allow extending multiple classes, you'll need to design your hierarchy carefully using single inheritance.
You'll create four files to organize your code:
AudioDevice.java: Create the base class that all audio-playing devices share. It should have:- A private field for
deviceName(String) - A constructor that accepts the device name
- A method
getDeviceName()that returns the name - A method
playSound()that prints:[deviceName]: Playing audio
- A private field for
MusicPlayer.java: Create a class that extends AudioDevice and adds music-specific features:- A private field for
currentSong(String) - A constructor that takes the device name and uses
super(deviceName) - A method
setSong(String song)that sets the current song - Override
playSound()to print:[deviceName]: Now playing - [currentSong]
- A private field for
SmartSpeaker.java: Create a class that extends MusicPlayer (not both MusicPlayer and some VoiceAssistant class - that would be multiple inheritance!). The smart speaker builds on the music player by adding voice features:- A private field for
assistantName(String) - A constructor that takes the device name and assistant name, using
super(deviceName) - A method
voiceCommand(String command)that prints:[assistantName]: Processing "[command]" - A method
getFullInfo()that prints:[deviceName] with [assistantName] assistant
- A private field for
Main.java: Demonstrate your multilevel inheritance chain. You'll receive three inputs: a device name (String), an assistant name (String), and a song name (String). Create a SmartSpeaker, set a song, then call these methods in order:getFullInfo()playSound()voiceCommand("skip to next")
You will receive three inputs: the device name, assistant name, and song name.
Notice how SmartSpeaker gains music capabilities by extending MusicPlayer in a chain (AudioDevice -> MusicPlayer -> SmartSpeaker), rather than trying to extend multiple unrelated classes. This is Java's approach to keeping inheritance clean and unambiguous!
Cheat sheet
Java only allows single inheritance - a class can extend only one other class. This prevents the Diamond Problem, where ambiguity arises if a class could inherit the same method from multiple parent classes.
// NOT allowed in Java - multiple inheritance
public class D extends B, C { } // ERROR!However, Java allows a class to implement multiple interfaces as an alternative:
// Valid in Java
public class Dog extends Animal implements Runnable, Comparable<Dog> {
// Can extend one class and implement multiple interfaces
}Java supports multilevel inheritance - creating inheritance chains:
public class AudioDevice { }
public class MusicPlayer extends AudioDevice { }
public class SmartSpeaker extends MusicPlayer { }
// SmartSpeaker inherits from both MusicPlayer and AudioDeviceTry it yourself
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String deviceName = scanner.nextLine();
String assistantName = scanner.nextLine();
String songName = scanner.nextLine();
// TODO: Create a SmartSpeaker with deviceName and assistantName
// TODO: Set the song using setSong()
// TODO: Call getFullInfo()
// TODO: Call playSound()
// TODO: Call voiceCommand("skip to next")
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System