Home  >  Article  >  Java  >  Does Java Allow True Multiple Inheritance?

Does Java Allow True Multiple Inheritance?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 22:09:02600browse

Does Java Allow True Multiple Inheritance?

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:

  • They facilitate adding new functionality to existing interfaces without breaking existing implementations.
  • They allow interfaces to provide default implementations for base behaviors that classes can override or implement as needed.
  • They enable a class to have multiple "is a" relationships from unrelated type trees.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn