Icognito 有一个很好的答案(我赞成)。我只想添加以下内容:
接口定义了任何实现对象必须具有的方法签名。它使您的代码可以在不知道任何其他内容的情况下调用这些对象上的方法。
一个类定义了方法签名并且可以定义方法体和属性。一个类可以实现一个接口。这使您能够将数据和操作代码保存在一起。
Icognito 的远程示例实际上比自行车更好。电视可能有这样的界面:
interface ITelevision {
void TogglePower();
void ChangeChannel( Int32 channel);
}
可能处理该接口的几个对象是一个或多个 TV 对象和一个 Remote 对象,例如:
class SonyTelevision: ITelevision {
public void TogglePower {
//Perform the operation to turn the TV on or off
}
public void ChangeChannel (Int32 channel) {
// Perform the operation of changing the channel
}
}
class ToshibaTelevision: ITelevision {
public void TogglePower {
//Perform the operation to turn the TV on or off
}
public void ChangeChannel (Int32 channel) {
// Perform the operation of changing the channel
}
}
class Remote {
private _television : Object; // here we don't care what kind of TV it is.
public void ToggleTvPower {
ITelevision tv = _television as ITelevision;
tv.TogglePower();
}
}
在上面,索尼和东芝制造商可能都有自己的电视类层次结构。但是,它们都实现了通用的 ITelevision 接口,这使得针对这些类的编码变得更加容易。
还要注意,接口意味着实现留给实现类。归根结底,只要每个人都实施 ITelevision,任何遥控器都可以控制任何电视。甚至未来的……
最后一点:抽象类与接口类似,抽象类需要后代提供方法体。但是,因为一个类可能只从一个父类继承,而一个类可以实现任意数量的接口。