我写了几行代码来实验和区分这两个东西:接口
和抽象类
。
我发现它们有相同的限制。
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
}
据我所发现的是,这两者之间没有明显的区别,因为它们都实现了相同的限制。我注意到的唯一区别是继承和实现。
- 一个类只能扩展一个基类。
- 一个类可以实现多个接口。
我理解的对吗?如果是这样,那么何时需要使用其中之一?
更新
我不知道这是否是正确答案,但你真的可以根据情况使用任何一种。面向对象编程真的很酷。
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
}