Inheritance in Java language

2020-03-31 04:37发布

We say that java follows a single inheritance model i.e. a Java class can extend only one class at max. and then say that every java class is inherited from Object class.

Suppose there are two classes A and B. Both A and B extend from Object. Now suppose A extends B. Doesn't it imply that A has multiple inheritence (A is inheriting from both B and Class Object)?

9条回答
Rolldiameter
2楼-- · 2020-03-31 04:48

Object A extends object B which extends Object. It's not multiple inheritance, it's hierarchy

查看更多
老娘就宠你
3楼-- · 2020-03-31 04:54
Excepting Object, which has no superclass, every class has one and |
only one direct superclass (single    inheritance). In the absence of any
other explicit superclass, every class is implicitly a subclass of Object.

aa

in your question A directly inherit B and Object class is inherited by B not by A..This is called transitive inheritance

查看更多
Anthone
4楼-- · 2020-03-31 04:54

Multiple Inheritance: (Not supported by Java)

Class A extends Object

Class B extends Object

Class C extends A, B

 Object
   /\
  /  \
 /    \
A      B     (Not supported by Java)
 \     /
  \   /
   \ /
    C

Multilevel/Transitive Inheritance:(Supported by Java)

Class B extends Object

Class A extedns B

 Object
    |
    |
    |
    B        (Supported by Java)
    |
    |
    |
    A
查看更多
女痞
5楼-- · 2020-03-31 05:00

Java doesn't let you extend more than 1 super-class. However, a class can implement multiple interfaces. You can create a structure of interfaces and abstract classes that let's you hack extending more than 1 class. Good luck!

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-03-31 05:03

Look at the difference between transitive inheritance (C inherits directly from B and transitively from A):

enter image description here

and multiple inheritance (C inheriting from both A and B):

enter image description here

Everything is just added on, except methods with the same signature, which are overridden. Even variables declared with the same name are added on, they're just said to be "hidden" but can still be accessed using casting, or the super keyword if it's the immediate parent.

查看更多
孤傲高冷的网名
7楼-- · 2020-03-31 05:08

The main problems with multiple inheritance is the ambiguity, when two classes define the same method and are being both overriden and the diamond problem. Java doesn't suffer from this as, it allows overriding only a single class. This obviously refers to direct overriding and doesn't deal with hierarchies of inheritance. This kind of inheritance (A overring B, B overriding and so on) isn't affected by any problems.

查看更多
登录 后发表回答