Multiple inheritance and diamond problem

Asked

Viewed 1,351 times

5

What’s wrong with the diamond? How do languages treat it? And they treat themselves differently because there is this difference?

  • Java 7 addresses the diamond problem by preventing multiple inheritance. In Java 8, with standard interface methods, this problem happened to occur, and it was treated by forcing to say where is getting the value, nothing implicit

  • @Jeffersonquesado has source of this java-8? It seems interesting, I would like to read more about.

  • @Articuno https://stackoverflow.com/q/16764791/4438007 ; I saw it in a blog post too, I think in official documentation, but I didn’t find it quickly

  • @Articuno, explicit resolution: http://www.lambdafaq.org/how-are-conflicting-method-declarations-resolved/

  • 1

    @Jeffersonquesado did the test, really forces to implement the default method and point to which method we will use.

  • 1

    Related: https://answall.com/a/3602/91, https://answall.com/q/173198/91 and https://answall.com/q/42970/91

Show 1 more comment

1 answer

4


If a class inherits two classes (concrete implementations), there may be conflict of implementations.

Example:

class ClasseBase1 
{
    public void Foo()
    {
        Console.WriteLine("ClasseBase1");
    }
}

class ClasseBase2 
{
    public void Foo()
    {
        Console.WriteLine("ClasseBase2");
    }
}

class ClasseDerivada : ClasseBase1, ClasseBase2
{
}

The class ClasseDerivada inherits two implementations of the method Foo, which creates a conflict because the compiler does not know which method to use.

In C# class multiple inheritance is prohibited, to avoid this problem diamond.

Now multiple inheritance of interfaces is allowed as interfaces are not implementations. The following code is valid.

Example:

interface IFoo1 
{
    public void Foo();
}

interface IFoo2
{
    public void Foo();
}

class ClasseDerivada : IFoo1, IFoo2
{
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.