Java Inheritance: Single Inheritance vs. Multiple Inheritance
During a job interview, a candidate was asked if Java supported multiple inheritance. The candidate responded with "No," citing that each class in Java extends Object and extending another class like "Class A extends Class B" means Class A inherits from both Class B and Object, which is considered multi-level inheritance, not multiple inheritance.
However, the interviewer challenged this answer, arguing that since Class B extends Object, extending Class B in Class A results in Class A inheriting from both Class B and Object, essentially constituting multiple inheritance.
Clarification
The candidate's answer was largely correct in the context of the interviewer's specific example. Multiple inheritance refers to a situation where a class inherits from two or more unrelated bases, creating a "diamond" structure in the inheritance hierarchy.
Java's Single Inheritance with Multiple Levels
In Java, however, inheritance is single-level with multiple levels. Class A extends Class B, which in turn extends Object. This creates a chain of inheritance, but Class A only inherits directly from Class B and indirectly from Object. This is not multiple inheritance.
Interfaces and "Default" Methods
While Java does not support traditional multiple inheritance, it does have interfaces and "default" methods on interfaces (introduced in Java 8). This feature allows classes to implement multiple interfaces and inherit their respective default methods.
However, this is still not true multiple inheritance because:
Conclusion
Java's inheritance model allows for single inheritance with multiple levels through the "extends" keyword and interfaces with default methods provide a form of "multiple inheritance light." However, it is important to distinguish these concepts from true multiple inheritance, where a class can inherit from multiple unrelated bases.
The above is the detailed content of Does Java Support Multiple Inheritance?. For more information, please follow other related articles on the PHP Chinese website!