Multiple Inheritance in Java

ByDasun De Silva

Dec 7, 2021

Java does not support multiple inheritance directly since it can be causes to ambiguty/diamond problem and multiple inheritance is very complex. Bit strange then what is this article title says.

Multiple Inheritance

When we discuss regarding multiple inheritance we can take below example.

There is a super class called School and it has a method called getSyllabusList() . Now there is another class named MixSchool and it inherit Class School and another class named PrivateSchool , inherites same School class. Now there is a Adgenda class which inherite both PrivateSchool and MixSchool. And when Syllabus call getSyllabusList there can be ambiguity. To over come this case Java avoids multiple inheritance. But if you still need same behaviour you can use interfaces in java. Therefore this article will shows you how Java accomplish multiple inheritance using interfaces.

class School {
	string name;
	public void getName(){
		return name;
	}
}

interface SyllabusList{
	List<String>  getSyllabusList();
}

class MixSchool extends School implements SyllabusList{
	String name;
	List<String>  getSyllabusList(){
		//In your class you can define getSyllabusList method as  you want. This is similar to virtual keyword in c++
		return null;
	} 
}

public class ExternalClass{
	public static void main(String args[]){
		MixSchool schoolA = new MixSchool();
		schoolA.getSyllabusList();
		schoolA.getName();
	}
}

Note: C++ supports multiple inheritance using virtual keyword. You can check this article for C++ multiple inheritance example.

Leave a Reply