Java and Multiple Inheritance
You recently encountered an interview question regarding Java's stance on multiple inheritance. While your response was mostly correct, let's delve deeper into the topic.
The scenario you described, where class A extends class B and class B extends Object, does not constitute multiple inheritance. Instead, this is an example of multi-level inheritance, where each level descends from the previous one.
Multiple inheritance implies that a class inherits from two or more bases that are unrelated or have previously diverged. In Java, since Object is always an ultimate base, multiple inheritance would mean inheriting from two different lines.
Internally, when the compiler resolves a member on an instance, it searches for that member in the object's type hierarchy. It first checks if the type possesses the member directly, and if not, it proceeds to the inherited levels.
While Java prohibits true multiple inheritance, it has evolved with interfaces that support "default methods" in Java 8. These default methods allow classes to "inherit" functionality from interfaces, providing a level of indirection that resembles multiple inheritance.
Defaual methods offer several advantages:
Although Java 8's default methods provide a form of multiple inheritance in practice, they do not solve the inherent complexities of true multiple inheritance, such as ambiguous superclass selection, construcor invocation order, and duplicate method inheritance.
The above is the detailed content of Does Java Allow True Multiple Inheritance?. For more information, please follow other related articles on the PHP Chinese website!