Skip to main content

Java : The diamond problem or Diamond Dead problem or deadly diamond of death?

The "diamond problem" (sometimes referred to as the "deadly diamond of death") is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
For example, in the context of GUI software development, a class Button may inherit from both classes Rectangle (for appearance) and Clickable (for functionality/input handling), and classes Rectangle and Clickable both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an overridden equals method in Rectangle or Clickable (or both), which method should be eventually called?
It is called the "diamond problem" because of the shape of the class inheritance diagram in this situation. In this case, class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.

Java 8 introduces default methods on interfaces. If A,B,C are interfaces, B,C can each provide a different implementation to an abstract method of A, causing the diamond problem. Either class D must re-implement the method (the body of which can simply forward the call to one of the super implementations), or the ambiguity will be rejected as a compile error. Prior to Java 8, Java was not subject to the Diamond problem risk, as Java does not support multiple inheritance.

Java Solution : We can resolve this issue by using a qualified name as we can understand by the below example.
The sample code in the answer by Óscar López is excellent. Here's another example:
class Base {
int x = 10;
}

interface Interface {
int x = 20;
}

class SingleInheritance implements Interface {
int y = 2 * x; // ok
}

class MultipleInheritance extends Base implements Interface {
int y = 2 * x; // compile-time error
int z = 2 * Interface.x; // ok
}

void aMethod(MultipleInheritance arg) {
System.out.println("arg.x = " + arg.x); // compile-time error
System.out.println("x = " + Interface.x); // ok
}
Java Itself provided a solution to the above problem as follows:
In Java 8, an interface now can declare both default methods and static method implementations. This brings a large chunk of the Diamond of Death problem into the language.
Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.
// A simple program to Test Interface default methods in java
interface TestInterface
{
    //abstract method
    public void square(int a);
    //default method
    default void show()
    {
      System.out.println("Default Method Executed");
    }
}
class TestClass implements TestInterface
{
    //implementation of square abstract method
    public void square(int a)
    {
        System.out.println(a*a);
    }
    public static void main(String args[]){
        TestClass d = new TestClass();
        d.square(4);
     //default method executed
        d.show();
    }
}
Output:
 16
Default Method Executed
The default methods were introduced to provide backward comparability so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. Default methods are also known as defender methods or virtual extension methods.

Default Methods and Multiple Inheritance:

In case both the implemented interfaces contain default methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method.
// A simple Java program to demonstrate multiple inheritance through default methods.
interface TestInterface1
{
// default method
    default void show()
    {
        System.out.println("Default TestInterface1");
    }
}
interface TestInterface2
{
// Default method
    default void show()
    {
        System.out.println("Default TestInterface2");
    }
}
 // Implementation class code
class TestClass implements TestInterface1, TestInterface2{
    // Overriding default show method
    public void show(){
        // use super keyword to call the show
        // method of TestInterface1 interface
        TestInterface1.super.show();
        // use super keyword to call the show
        // method of TestInterface2 interface
        TestInterface2.super.show();
    }
    public static void main(String args[]){
        TestClass d = new TestClass();
        d.show();
    }
}
Output:
Default TestInterface1
Default TestInterface2
Important Points:
  1. Interfaces can have default methods with implementation from java 8 onwards.
  2. Interfaces can have static methods as well similar to static method of classes.
  3. Default methods were introduced to provide backward comparability for old interfaces so that they can have new methods without effecting existing code.
REFERENCES:

Comments

Top 5 Most Read Posts

Who is Peter Lynch and what is his philosophy in equity market investment? 25 Golden Rules of the most successful Fund Manager.

Peter Lynch (born January 19, 1944) is an American investor, mutual fund manager, and philanthropist. As the manager of the Magellan Fund at Fidelity Investments between 1977 and 1990, Lynch averaged a 29.2% annual return, consistently more than doubling the S&P 500 stock market index and making it the best-performing mutual fund in the world. During his 13 year tenure, assets under management increased from $18 million to $14 billion. He also co-authored a number of books and papers on investing and coined a number of well known mantras of modern individual investing strategies, such as Invest in what you know and ten bagger. Lynch is consistently described as a "legend" by the financial media for his performance record. Base on his career I have compiled his investing rules here. 25 GOLDEN RULES by @Peter Lynch 1: Nobody can predict interest rates, the future direction of the economy or the stock market. Dismiss all such forecasts & concentrate on what's actual...

What is version checking in Hibernate ?

Version checking used in hibernate when more then one thread trying to access same data. For example : User A edit the row of the TABLE for update ( In the User Interface changing data This is user thinking time) and in the same time User B edit the same record for update and click the update. Then User A click the Update and update done. Change made by user B is gone. In hibernate you can prevent slate object updation using version checking. Check the version of the row when you are updating the row. Get the version of the row when you are fetching the row of the TABLE for update. On the time of updation just fetch the version number and match with your version number (on the time of fetching).

Fundamental Analysis : Asian Paints Ltd.

Asian Paints group is the largest paint manufacturer in India also engaged in the business of manufacturing of varnishes, enamels or lacquers, surfacing preparation, organic composite solvents and thinners. It operates in 15 countries and has 26 paint manufacturing facilities in the world serving consumers in over 60 countries. Besides Asian Paints, the group operates around the world through its various brands viz. Asian Paints Berger, Apco Coatings, SCIB Paints, Taubmans, Causeway Paints and Kadisco Asian Paints. It also manufactures metal sanitary ware such as bath, sinks, washbasins and similar articles. Recently introduced Lightings, Furnishings and Furniture thus adding more products in the Home décor and Interior Design category. Market Cap ₹ 244,763 Cr. Current Price ₹ 2,552 High / Low ₹ 2,873 / 1,483 Stock P/E 89.0 Book Value ₹ 115 Dividend Yield 0.47 % ROCE 33.8 % ROE 27.5 % Face Value ₹ 1.00 Price to book value 22.2 EPS ₹ 28.7 High price all time ₹ 2,873 Low price all time ₹...

Understanding NPCI and UPI Technology

In the vibrant landscape of India's digital revolution, the National Payments Corporation of India (NPCI) stands tall as a pioneer, shaping the future of financial transactions. Central to its transformative journey is the Unified Payments Interface (UPI) technology, a game-changer in the realm of peer-to-peer payments. Let's embark on a journey to unravel the intricacies of NPCI, UPI, and the fascinating world of digital payments terminology. National Payments Corporation of India (NPCI): A Pillar of Digital India: Established in 2008, NPCI has been instrumental in architecting India's digital payments infrastructure. As a not-for-profit organization, its mandate extends to orchestrating seamless retail payments and settlement systems across the nation. Driving Financial Inclusion: NPCI's vision transcends boundaries, aiming to empower every Indian with access to secure and efficient payment solutions. Its initiatives, such as UPI and IMPS, have been pivotal in bridgin...

What is wrong with HDFC securities? Are they doing some fraudulent activities or just causing issues with their platform as usually it don't work during market hours?

I have opened a DEMAT account with HDFC Securities in 2019 as HDFC group is well known for the customer services and I also hold a salary account with HDFC Bank, DEMAT account with the following conditions/offers as expressed by the executive. Trading Account Opening Charges (One Time) :  ₹999 (At that time it offered on lower price, I forget the exact price) Trading Annual Maintenance Charges AMC (Yearly Fee) : ₹0 Demat Account Opening Charges (One Time) : ₹0 Demat Account Annual Maintenance Charges AMC (Yearly Fee) : ₹750, nil if portfolio value below ₹2 lacs. Equity Delivery : 0.50% Equity Intraday : 0.05% Equity Futures : 0.05% Equity Options : ₹100 per lot or 1% of the premium (whichever is higher) Currency Futures : ₹23 per contract Currency Options : ₹20 per contract Commodity Futures : 0.02% for Intraday / 0.025% for positional Commodity Options : 0.02% for Intraday / 0.025% for positional It was going good but after 2-3 months I got to know that there are...