Showing posts with label dimond problem. Show all posts
Showing posts with label dimond problem. Show all posts

Wednesday 14 March 2018

Why Java does not support multiple inheritance ?

Why Java does not support multiple inheritance ?

Many times this question will make you uncomfortable in Java interview. Though most of us know the rule of multiple inheritance, the reason behind this concept is not known to many of the students.

The above question in fact can be re-framed as,

"Why Java does not support multiple inheritance but can implement multiple interfaces?"


Traditionally when we do programming in c++, we have option of extending more than one classes and utilize the services from both the classes.so what's the advantages of this design in Java that a class can only extends one class ? Since interface is a pure kind of class(abstract class actually), why not limit the number of interfaces implementation just like class extension ?

Being able to extend only one base class is one way of solving the "dimond problem"

This is a problem which occurs when a class extends two base classes which both implement the same method. Then how do you know which one to call ?

A.java:


public class A {

    public int getValue() { return 0; }

}

B.java:

public class B {

    public int getValue() { return 1; }

}

C.java:


public class C extends A, B {

    public int doStuff() {

        return super.getValue(); // Which superclass method is called?

    }

}

Since interfaces cannot have implementations, this same problem does not arise. If two interfaces contain methods that have identical signatures, then there is effectively only one method and there still is no conflict.

Hope this makes sense !!

Education is a continuous process !!


Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...