Multiple Inheritance Ambiguity


  • 0

    How multiple inheritance can cause ambiguity in few scenarios? Does java allows multiple inheritance? If yes, then how it is implemented?


  • 2

    Multiple inheritance can cause ambiguity in few scenarios. One of the most common scenario is Diamond problem.

    Consider the below diagram which shows multiple inheritance as Class D extends both Class B & C. Now lets assume we have a method in class A and class B & C overrides that method in their own way. Wait!! here the problem comes – Because D is extending both B & C so if D wants to use the same method which method would be called (the overridden method of B or the overridden method of C). Ambiguity.

    0_1498884803981_89201dc6-0abc-476e-a296-3cc3291e621d-image.png

    Multiple Inheritance can be achieved in java using interfaces.

    What is interface in java?

    Interface is a restricted form of a class can contains only static constants and abstract methods. It does not implement any methods, only methods declarations are allowed.

    Example:

    public interface InterfaceExample {
        abstract public void interfaceMethod();
    }
    

  • 0
    S

    https://en.wikipedia.org/wiki/Multiple_inheritance

    TL;TD: The classical scenario is the "diamond inheritence problem" in which scenario the derived class has two the same inherited methods and the decision of using either is not determined.

    Solutions to that differs from language to language. In static languages like c++ and go, explicit overridden is required at compile time. In dynamic language, the resolution order is usually the same as the declaration order at definition. For example, in python def D(B, C): pass, mean B overshadows C.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.