| 1. |
Write a program in Java to show the Diamond Problem. |
|
Answer» The Diamond Problem is a problem of Multiple inheritance. It is one of the major reasons why multiple inheritance is not supported in Java. Have a look at the diagram given below. Here, class D extends from classes B and C and they extend from Class A. Let us say that class A has a function called print(). This function is overridden in Class B and C respectively. Now, when class D extends B and C both, say it calls super.print(). Which function should be called? This is an anomaly called the diamond problem or deadly diamond of death. Java Code for Diamond Problem class A {public void print() { System.out.println("Class A print method"); } } class B extends A { @Override public void print() { System.out.println("Class B print method"); } } class C extends A { @Override public void print() { System.out.println("Class C print method"); } } //multiple inheritance not allowed in Java class D extends A,B { @Override public void print() { System.out.println("Class D print method"); } } class Main { public static void main(String args[]) { // Your code goes here D obj = new D(); obj.print(); } } Output This compilation error occurs because multiple inheritance is not allowed in Java. |
|