Java Multiple Inheritance - How To Extend Multiple Classes
In Java you can’t extend multiple classes but you CAN implement multiple interfaces instead.
Does Java have multiple inheritance? Yes, sort of.
- In Java you can’t inherit from multiple classes because two superclasses would then have the ability to write / overwrite the same fields.
- In Java you CAN inherit from multiple interfaces because interfaces don’t contain fields and will not have the problem mentioned above.
If you want to learn about Java inheritance in general check out our other guide here: Java Inheritance - How To Extend A Class.
Here is an example of using multiple inheritance in Java with interfaces:
interface Apples {
default void processData() {
System.out.println("Process apples");
}
}
interface Oranges {
default void processData() {
System.out.println("Process oranges");
}
}
class Multi1 implements Apples, Oranges {
public void processData() {
Apples.super.processData();
Oranges.super.processData();
System.out.println("Process Kiwi");
}
public static void main(String args[]) {
Multi1 d = new Multi1();
d.processData();
}
}
Output should look like this:
Process apples
Process oranges
Process Kiwi