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
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) gives an idea on why multiple inheritance is not supported in Java.
According to Gosling:
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
If multiple inheritance is allowed and When you create an object by instantiating that class, that object will inherit fields from all of the class's superclasses. It will cause two issues.
Multiple inheritance of implementation: Ability to inherit method definitions from multiple classes
Problems with this approach: name conflicts and ambiguity. If a subclass and superclass contain same method name (and signature), compiler can't determine which version to invoke.
But java supports this type of multiple inheritance with default methods, which have been introduced 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 do not have to worry about problems that result from multiple inheritance of state here.
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.