Java doesn't allow multiple inheritance, but it allows implementing multiple interfaces. Why?
相关问题
- Delete Messages from a Topic in Apache Kafka
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
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
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.
Because inheritance is overused even when you can't say "hey, that method looks useful, I'll extend that class as well".
One of my college instructors explained it to me this way:
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.
For example two class A,B having same method m1(). And class C extends both A, B.
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.
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.