One class may implement any number of interfaces, even if those interfaces extend other interfaces as well. Multiple inheritance is not possible only with classes.
// This is not allowed
class A { void A() {} }
class B { void B() {} }
class C : A, B {}
// This is allowed
interface IA { void A(); }
interface IB { void B(); }
class A : IA, IB
{
public void A() {}
public void B() {}
}
The diamond problem exists with classes because there is a possibility of clashing implementations (if A
and B
have the same method and C
extends both, which method does it take?). Interfaces, on the other hand, simply require an implementing type to have the methods that they declare.
If the exact same method is defined in two interfaces, and a class implements both interfaces, that doesn't matter. All the class needs to do is provide an implementation for the method so that code can be written to call that method. Meaning, this works:
interface IA { void Method(int x); }
interface IB { void Method(int x); }
class A : IA, IB
{
public void Method(int x)
{
Console.WriteLine(x);
}
}
Note that a class may still inherit from one other class, plus any number of interfaces:
class A : B, IA, IB {}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…