类可以实现(implement)接口。通过接口,你可以强制地指明类遵守某个契约。你可以在接口中声明一个方法,然后要求类去具体实现它。
「接口不可以被实例化,实现接口必须重写接口中的抽象方法」
interface Play {
plays (difang:string) : void;
}
class Playy implements Play {
plays(difang: string): void {
console.log(`我们要去 ${difang}玩!!!`)
}
}
const pl : Playy = new Playy();
pl.plays('北京')
类和接口的区别
- 类可以实现(implement)多个接口,但只能扩展(extends)自一个抽象类。
- 抽象类中可以包含具体实现,接口不能。
- 抽象类在运行时是可见的,可以通过 instanceof判断。接口则只在编译时起作用。
- 接口只能描述类的公共(public)部分,不会检查私有成员,而抽象类没有这样的限制。