【发布时间】:2018-10-11 03:48:32
【问题描述】:
我写了几行代码来试验和区分这两者:interface 和 abstract class。
我发现他们有同样的限制。
interface IPerson {
name: string;
talk(): void;
}
interface IVIP {
code: number;
}
abstract class Person {
abstract name: string;
abstract talk(): void;
}
class ManagerType1 extends Person {
// The error I get is that I need to implement the talk() method
// and name property from its base class.
}
class ManagerType2 implements IPerson {
// The error I get is that I need to implement the talk() method
// and the name property from the interface.
}
class ManagerType3 implements IPerson, IVIP {
// Now the error I get is that I need to implement all the
// properties and methods of the implemented interfaces to the derived class
}
正如我发现的那样,这两者之间没有明显的区别,因为它们都实现了相同的限制。我唯一注意到的是继承和实现。
- 一个类只能扩展为一个基类
- 一个类可以实现多个接口。
我没听错吗?如果是这样,我什么时候需要使用?
更新
我不知道这是否是正确的答案,但您可以根据自己的情况真正使用 BOTH。 OOP 真的很酷。
class ManagerType3 extends Person implements IPerson, IVIP {
// Now the restriction is that you need to implement all the abstract
// properties and methods in the base class and all
// the properties and methods from the interfaces
}
【问题讨论】:
-
除了限制基类可以提供实现/部分实现,接口只定义shape/contract
-
@AlekseyL。是的,非常感谢,我发现接口是用于标准的,与抽象类相同,但是您可以为每个派生类添加一些持久的方法。
标签: typescript oop