简体   繁体   中英

By default any class extends Object class. Doesn't it mean java supports multiple inheritance?

Everybody knows that in java we can only extend "ONE" class.

But for the sake of understanding:

  1. Any Java class implicitly extends java.lang.Object
  2. If class A extends class B, wouldn't class A extend both class B and java.lang.Object implicitly ?

In such a case we are extending two classes by default.

Why is it allowed if Java doesn't support multiple inheritance ?

No, Java prevents a class from directly extending more than one super class. Class A can extend a class B which extends class C. This is still single inheritance. All the classes form a tree, where the root is the Object class, and each class (except of Object) has exactly one direct super-class (or parent class), which is either Object or some other class.

That would be a multilevel inheritance . You are mistaking multiple to multilevel.

A->B->C //This is multilevel inheritance which you are talking about

Multiple inheritance is like (which is not possible in java)

     A
   |   |
   B   C

Java doesn't support multiple inheritance that makes any ambiguous cases to fade away. But careful implementation of implement keyword for implementing does give feel of multiple inheritance

Conclusion:

Class A can extend a class B which extends class C. This is still single inheritance. All the classes form a tree, where the root is the Object class, and each class (except of Object) has exactly one direct super-class (or parent class)

每当类A扩展类B时,类A不再扩展Java.lang.Object,但是:由于每个类都扩展了Java.lang.Object,如您之前所说,类B将扩展Java.lang.Object,因此类A是扩展Java.lang.Object。仍然是该特定类的子类。

"Implicitly extends Object by default" means that if you don't see the extends keyword in the class declaration it "invisibly but directly" extends Object. If you see the extends keyword, the class does not directly extend Object, but the class mentioned in the extends clause. Now you have to traverse that hierarchy and at one point, you'll find a parent class with no "extends", and there the implicit inheritance strikes again.

All classes in a hierarchy transitively extend Object, but only the root does it directly. Transitively because all subclasses inherit all the traits of their parents, including their parent classes and implemented interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM