Inheritance is mostly important for re-usability of code and functionality
and multiple inheritance was helping to re-use code from more than one class,
but in Interface I didn't find any such feature except that a class can inherit
from more than one interface.
确实,接口促进了代码的可重用性(尤其是与多态性结合时,继承可以创造奇迹!)。我可以举出另一种接口可能有益的情况:回调。
由于我们在 C# 中有委托,我怀疑是否有任何 C# 开发人员会使用接口作为回调的媒介(可能是使用 C# 1.0 的 C# 开发人员)。但是对于 Java 开发人员,他们将如何在没有委托的情况下实现回调?答案:接口。
使用委托的回调
public delegate int Transformer (int x);
class Util
{
public static void Transform (int[] values, Transformer t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t (values[i]);
}
}
class Test
{
static void Main()
{
int[] values = { 1, 2, 3 };
Util.Transform (values, Square);
foreach (int i in values)
Console.Write (i + " ");
}
static int Square (int x) { return x * x; }
}
使用接口的回调
public interface ITransformer
{
int Transform (int x);
}
public class Util
{
public static void TransformAll (int[] values, ITransformer t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t.Transform (values[i]);
}
}
class Squarer : ITransformer
{
public int Transform (int x) { return x * x; }
}
static void Main()
{
int[] values = { 1, 2, 3 };
Util.TransformAll (values, new Squarer());
foreach (int i in values)
Console.WriteLine (i);
}
如需进一步了解回调,请参阅C# Callbacks with Interfaces and Delegates 和Implement callback routines in Java。
注意:本文中的示例代码摘自《C# 4.0 in a Nutshell》一书(这也是一本很好的 C# 参考资料)。
知名开发人员警告我们继承的危险:
Why extends is evil Allen Holub
OOP The Good Parts: Message Passing, Duck Typing, Object Composition, and not Inheritance Nick Fitzgerald
Seven deadly sins of programming - Sin #2: Overuse of Inheritance Eric Gunnerson