Does Java support Mulitiple Inheritance?

后端 未结 5 1804
半阙折子戏
半阙折子戏 2021-01-25 15:03

From the Java fact that all class in Java have a parent class as Object. But the same Java says that it doesn\'t support multiple inheritance. But what this code me

相关标签:
5条回答
  • 2021-01-25 15:40

    Java does not support Multiple Inheritance by a developer. Behind the scenes, the compiler ensures everything extends Object.

    Basically, the compiler will modify

    public Class A extends Object, B to practically be Class A extends B and Class B extends Object.

    0 讨论(0)
  • 2021-01-25 15:41

    Multiple inheritance means that one class extends two other classes. Multiple inheritance is allowed in e.g. C++. But this is not that same as:

    class Object {
    ...
    }
    
    class B extends Object { //default, not need to be there
    ...
    }
    
    class A extends B {
    ...
    }
    
    0 讨论(0)
  • 2021-01-25 15:48

    From the Java fact that all class in Java have a parent class as Object

    Actually no, that's not true. Object is only the default parent class. If you explicitly specify a parent, as in your example (A extends B), then the class you're defining no longer has Object as an immediate parent.

    However, the fact that Object is the default means that it's impossible to create a class (except for Object itself) without a superclass. Since every class must have a superclass, every class has to have Object as an ancestor at some level.

    0 讨论(0)
  • 2021-01-25 15:58

    No, this is single inheritance. A inherits from B, B inherits from Object.

    Multiple inheritance would be A extends from B and C, where B and C don't inherit from each other, which can cause the Diamond Problem:

    If B defines a method foo() and C also defines a method foo(), and I do this:

    new A().foo();
    

    Which foo() implementation will be used?

    This is a huge problem in many languages, so the Java designers decided not to allow multiple inheritance.

    0 讨论(0)
  • 2021-01-25 16:01

    Multiple inheritance is having more than 1 direct base class. The example you have given is single inheritance.

    For example, if you have 3 classes A, B and C...

    public class A extends B
    

    with

    public class B extends C
    

    is still just single inheritance.
    Multiple inheritance would be

    public class A extends B, C
    
    0 讨论(0)
提交回复
热议问题