抽象类和接口在定义属性方面的不同点
- 抽象类:
- 抽象类可以包含属性的实现(即可以有属性的初始化),也可以有抽象属性(只有声明,没有实现,且必须在抽象类的子类中实现)。
- 抽象类中的属性可以有访问修饰符(如
public
、private
、protected
),用来控制属性的访问权限。
- 接口:
- 接口只能定义属性的签名,不能包含属性的实现。
- 接口中的属性默认都是
public
的,并且不能使用其他访问修饰符。
在抽象类中定义只读属性与可选属性
- 只读属性:
abstract class Animal {
// 只读属性
public readonly name: string;
constructor(name: string) {
this.name = name;
}
}
- 可选属性:
abstract class Shape {
// 可选属性
public color?: string;
abstract draw(): void;
}
在接口中定义只读属性与可选属性
- 只读属性:
interface Point {
// 只读属性
readonly x: number;
readonly y: number;
}
- 可选属性:
interface User {
name: string;
// 可选属性
age?: number;
}