orientação-a-objetos – Multiple inheritance and the diamond problem

Question:

What is the diamond problem? How do languages ​​treat you? And do they treat each other differently because there is this difference?

Answer:

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

Example:

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

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

class ClasseDerivada : ClasseBase1, ClasseBase2
{
}

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

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

Multiple inheritance of interfaces is now 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
{
}
Scroll to Top