Java doesn't allow multiple inheritance, but it allows implementing multiple interfaces. Why?
-
2I edited the question title to make it more descriptive.Bozho– Bozho2010-03-25 12:45:25 +00:00Commented Mar 25, 2010 at 12:45
-
4Interestingly, in the JDK 8, there will be extension methods which will allow the definition of implementation of interface methods. Rules are been defined to govern multiple inheritance of behavior, but not of state (which I understand is more problematic.Edwin Dalorzo– Edwin Dalorzo2012-07-31 12:48:06 +00:00Commented Jul 31, 2012 at 12:48
-
1Before you guys waste time on answers which only tell you "How java acheives multiple inheritance "... I suggest you to go down to @Prabal Srivastava answer that logically gives you what must be happening internally, to not allow classes this right... and only allow interfaces the right to allow multiple inheritance.Yo Apps– Yo Apps2019-11-27 15:09:49 +00:00Commented Nov 27, 2019 at 15:09
-
@YoApps That answer has it back to front. It was a design decision, and the compiler and JVM implementation followed. Most of the other answers here follow a similar cart-before-horse logic. All this is essentially tautologous. The real answer is that it was a design decision to avoid the diamond-inheritance issues, which are legion.user207421– user2074212022-06-19 04:30:13 +00:00Commented Jun 19, 2022 at 4:30
21 Answers
Because interfaces specify only what the class is doing, not how it is doing it.
The problem with multiple inheritance is that two classes may define different ways of doing the same thing, and the subclass can't choose which one to pick.
16 Comments
One of my college instructors explained it to me this way:
Suppose I have one class, which is a Toaster, and another class, which is NuclearBomb. They both might have a "darkness" setting. They both have an on() method. (One has an off(), the other doesn't.) If I want to create a class that's a subclass of both of these...as you can see, this is a problem that could really blow up in my face here.
So one of the main issues is that if you have two parent classes, they might have different implementations of the same feature — or possibly two different features with the same name, as in my instructor's example. Then you have to deal with deciding which one your subclass is going to use. There are ways of handling this, certainly — C++ does so — but the designers of Java felt that this would make things too complicated.
With an interface, though, you're describing something the class is capable of doing, rather than borrowing another class's method of doing something. Multiple interfaces are much less likely to cause tricky conflicts that need to be resolved than are multiple parent classes.
6 Comments
Because inheritance is overused even when you can't say "hey, that method looks useful, I'll extend that class as well".
public class MyGodClass extends AppDomainObject, HttpServlet, MouseAdapter,
AbstractTableModel, AbstractListModel, AbstractList, AbstractMap, ...
10 Comments
The answer of this question is lies in the internal working of java compiler(constructor chaining). If we see the internal working of java compiler:
public class Bank {
public void printBankBalance(){
System.out.println("10k");
}
}
class SBI extends Bank{
public void printBankBalance(){
System.out.println("20k");
}
}
After compiling this look like:
public class Bank {
public Bank(){
super();
}
public void printBankBalance(){
System.out.println("10k");
}
}
class SBI extends Bank {
SBI(){
super();
}
public void printBankBalance(){
System.out.println("20k");
}
}
when we extends class and create an object of it, one constructor chain will run till Object class.
Above code will run fine. but if we have another class called Car which extends Bank and one hybrid(multiple inheritance) class called SBICar:
class Car extends Bank {
Car() {
super();
}
public void run(){
System.out.println("99Km/h");
}
}
class SBICar extends Bank, Car {
SBICar() {
super(); //NOTE: compile time ambiguity.
}
public void run() {
System.out.println("99Km/h");
}
public void printBankBalance(){
System.out.println("20k");
}
}
In this case(SBICar) will fail to create constructor chain(compile time ambiguity).
For interfaces this is allowed because we cannot create an object of it.
For new concept of default and static method kindly refer default in interface.
Hope this will solve your query. Thanks.
1 Comment
You can find accurate answer for this query in oracle documentation page about multiple inheritance
- Multiple inheritance of state: Ability to inherit fields from multiple classes
In this case, When you create an object : It will inherit fields from all of the superclasses. It will cause two issues.
a. What if methods or constructors from different super classes instantiate the same field? b. Which method or constructor will take precedence?
- Multiple inheritance of implementation: Ability to inherit method definitions from multiple classes
This approach causes name conflicts and ambiguity. If a subclass and superclass contain same method name (and signature), compiler can't determine which version to invoke.
Java supports this type of multiple inheritance with default methods, since Java 8 release. The Java compiler provides some rules to determine which default method a particular class uses.
Refer to below SE post for more details on resolving diamond problem:
What are the differences between abstract classes and interfaces in Java 8?
- Multiple inheritance of type: Ability of a class to implement more than one interface.
Since interface does not contain mutable fields, you need not worry about problems that result from multiple inheritance of state here.
2 Comments
Java does not support multiple inheritance because of two reasons:
- In java, every class is a child of
Objectclass. When it inherits from more than one super class, sub class gets the ambiguity to acquire the property of Object class.. - In java every class has a constructor, if we write it explicitly or not at all. The first statement is calling
super()to invoke the supper class constructor. If the class has more than one super class, it gets confused.
So when one class extends from more than one super class, we get compile time error.
2 Comments
super() is arbitrary ("just because"). The requirement could be removed or have a syntax that supports naming parent types. I would say the reverse: super exists because language does not support multiple class inheritance.Java supports multiple inheritance through interfaces only. A class can implement any number of interfaces but can extend only one class.
Multiple inheritance is not supported because it leads to deadly diamond problem. However, it can be solved but it leads to complex system so multiple inheritance has been dropped by Java founders.
In a white paper titled “Java: an Overview” by James Gosling in February 1995(link - page 2) gives an idea on why multiple inheritance is not supported in Java.
According to Gosling:
"JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions."
1 Comment
Implementing multiple interfaces is very useful and doesn't cause much problems to language implementers nor programmers. So it is allowed. Multiple inheritance while also useful, can cause serious problems to users (dreaded diamond of death). And most things you do with multiple inheritance can be also done by composition or using inner classes. So multiple inheritance is forbidden as bringing more problems than gains.
6 Comments
ToyotaCar and HybridCar both derived from Car and overrode Car.Drive, and if PriusCar inherited both but didn't override Drive, the system would have no way of identifying what the virtual Car.Drive should do. Interfaces avoid this problem by avoiding the italicized condition above.void UseCar(Car &foo); cannot be expected to include disambiguation between ToyotaCar::Drive and HybridCar::Drive (since it should often neither know nor care that those other types even exist). A language could, as C++ does, require that code with ToyotaCar &myCar wishing to pass it to UseCar must first cast to either HybridCar or ToyotaCar, but since ((Car)(HybridCar)myCar).Drive` and ((Car)(ToyotaCar)myCar).Drive would do different things, that would imply that the upcasts were not identity-preserving.It is said that objects state is referred with respect to the fields in it and it would become ambiguous if too many classes were inherited. Here is the link
http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
Comments
Since this topic is not close I'll post this answer, I hope this helps someone to understand why java does not allow multiple inheritance.
Consider the following class:
public class Abc{
public void doSomething(){
}
}
In this case the class Abc does not extends nothing right? Not so fast, this class implicit extends the class Object, base class that allow everything work in java. Everything is an object.
If you try to use the class above you'll see that your IDE allow you to use methods like: equals(Object o), toString(), etc, but you didn't declare those methods, they came from the base class Object
You could try:
public class Abc extends String{
public void doSomething(){
}
}
This is fine, because your class will not implicit extends Object but will extends String because you said it. Consider the following change:
public class Abc{
public void doSomething(){
}
@Override
public String toString(){
return "hello";
}
}
Now your class will always return "hello" if you call toString().
Now imagine the following class:
public class Flyer{
public void makeFly(){
}
}
public class Bird extends Abc, Flyer{
public void doAnotherThing(){
}
}
Again class Flyer implicit extends Object which has the method toString(), any class will have this method since they all extends Object indirectly, so, if you call toString() from Bird, which toString() java would have to use? From Abc or Flyer? This will happen with any class that try to extends two or more classes, to avoid this kind of "method collision" they built the idea of interface, basically you could think them as an abstract class that does not extends Object indirectly. Since they are abstract they will have to be implemented by a class, which is an object (you cannot instanciate an interface alone, they must be implemented by a class), so everything will continue to work fine.
To differ classes from interfaces, the keyword implements was reserved just for interfaces.
You could implement any interface you like in the same class since they does not extends anything by default (but you could create a interface that extends another interface, but again, the "father" interface would not extends Object"), so an interface is just an interface and they will not suffer from "methods signature colissions", if they do the compiler will throw a warning to you and you will just have to change the method signature to fix it (signature = method name + params + return type).
public interface Flyer{
public void makeFly(); // <- method without implementation
}
public class Bird extends Abc implements Flyer{
public void doAnotherThing(){
}
@Override
public void makeFly(){ // <- implementation of Flyer interface
}
// Flyer does not have toString() method or any method from class Object,
// no method signature collision will happen here
}
Comments
For the same reason C# doesn't allow multiple inheritence but allows you to implement multiple interfaces.
The lesson learned from C++ w/ multiple inheritence was that it lead to more issues than it was worth.
An interface is a contract of things your class has to implement. You don't gain any functionality from the interface. Inheritence allows you to inherit the functionality of a parent class (and in multiple-inheritence, that can get extremely confusing).
Allowing multiple interfaces allows you to use Design Patterns (like Adapter) to solve the same types of issues you can solve using multiple inheritence, but in a much more reliable and predictable manner.
10 Comments
D1 and D2 both inherit from B, and each overrides a function f, and if obj is an instance of a type S which inherits from both D1 and D2 but does not override f, then casting a reference to S to D1 should yield something whose f uses the D1 override, and casting to B shouldn't change that. Likewise casting a reference S to D2 should yield a something whose f uses the D2 override, and casting to B shouldn't change that. If a language didn't need to allow virtual members to be added...For example two class A,B having same method m1(). And class C extends both A, B.
class C extends A, B // for explaining purpose.
Now, class C will search the definition of m1. First, it will search in class if it didn't find then it will check to parents class. Both A, B having the definition So here ambiguity occur which definition should choose. So JAVA DOESN'T SUPPORT MULTIPLE INHERITANCE.
1 Comment
in simple manner we all know, we can inherit(extends) one class but we can implements so many interfaces.. that is because in interfaces we don't give an implementation just say the functionality. suppose if java can extends so many classes and those have same methods.. in this point if we try to invoke super class method in the sub class what method suppose to run??, compiler get confused example:- try to multiple extends but in interfaces those methods don't have bodies we should implement those in sub class.. try to multiple implements so no worries..
Comments
Multiple inheritance is not supported by class because of ambiguity. (this point is explained clearly in above answers using super keyword)
Now for interfaces,
upto Java 7, interfaces could not define the implementation of methods. So if class implements from multiple interfaces having same method signature then implementation of that method is to be provided by that class.
from java 8 onwards, interfaces can also have implementation of methods. So if class implements two or more interfaces having same method signature with implementation, then it is mandated to implement the method in that class also.
From Java 9 onwards, interfaces can contain Static methods, Private methods, Private Static methods.
Modifications in features of Interfaces (over java version-7,8,9)
Comments
Because an interface is just a contract. And a class is actually a container for data.
1 Comment
Consider a scenario where Test1, Test2 and Test3 are three classes. The Test3 class inherits Test2 and Test1 classes. If Test1 and Test2 classes have same method and you call it from child class object, there will be ambiguity to call method of Test1 or Test2 class but there is no such ambiguity for interface as in interface no implementation is there.
Comments
Java does not support multiple inheritance , multipath and hybrid inheritance because of the following ambiguity problem.
Scenario for multiple inheritance: Let us take class A , class B , class C. class A has alphabet(); method , class B has also alphabet(); method. Now class C extends A, B and we are creating object to the subclass i.e., class C , so C ob = new C(); Then if you want call those methods ob.alphabet(); which class method takes ? is class A method or class B method ? So in the JVM level ambiguity problem occurred. Thus Java does not support multiple inheritance.
Reference Link: https://plus.google.com/u/0/communities/102217496457095083679
Comments
Take for example the case where Class A has a getSomething method and class B has a getSomething method and class C extends A and B. What would happen if someone called C.getSomething? There is no way to determine which method to call.
Interfaces basically just specify what methods a implementing class needs to contain. A class that implements multiple interfaces just means that class has to implement the methods from all those interfaces. Whci would not lead to any issues as described above.
10 Comments
the image explaining the problem with multiple inheritances.
What is the inherited member of the derived class? it is still private or publically available in the derived class?
For not getting this type of problem in Java they removed multiple inheritance. This image is a simple example of an object-oriented programming problem.
1 Comment
* This is a simple answer since I'm a beginner in Java *
Consider there are three classes X,Y and Z.
So we are inheriting like X extends Y, Z
And both Y and Z is having a method alphabet() with same return type and arguments. This method alphabet() in Y says to display first alphabet and method alphabet in Z says display last alphabet.
So here comes ambiguity when alphabet() is called by X. Whether it says to display first or last alphabet???
So java is not supporting multiple inheritance.
In case of Interfaces, consider Y and Z as interfaces. So both will contain the declaration of method alphabet() but not the definition. It won't tell whether to display first alphabet or last alphabet or anything but just will declare a method alphabet(). So there is no reason to raise the ambiguity. We can define the method with anything we want inside class X.
So in a word, in Interfaces definition is done after implementation so no confusion.
Comments
It is a decision to keep the complexity low. With hybrid inheritance, things would have been more complicated to implement, and anyways what is achievable by multiple inheritances is also with other ways.