继承
class Student extends Person {classNumber: string;constructer(id:number, name: string, classNumber: string) {super(id,name);this.classNumber = classNumber;} introduce(): string {return super.introduce() + `, and I am a student`;}}let student = new Student(1, 'xiaoming','三年二班');
console.log(student.introduce());
注意:
类的继承需要使用关键字extends
子类构造器中需使用super()调用父类构造器对继承自父类的属性进行初始化。
在子类可以使用this关键字访问继承自父类的属性和方法
在子类中可以使用super关键字访问父类定义的方法
class Person {private id: number;protected name: string;public age: number;constructor(id: number, name: string, age: number) {this.id = id;this.name = name;this.age = age;}
}class Student extends Person {}
说明:
private 修饰的属性或方法是私有的,只能在声明它的类中被访问
protected修饰的属性或方法是受保护的,只能在声明它的类和其子类中被访问。
public修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是public的
接口(interface)
接口(interface)是面向对象编程中的另一个重要概念。接口通常会作为一种契约或规范让类(class)去遵守,确保类实现某些特定的行为或功能。
interface Person {id: number;name: string;age: number;introduce(): void; }
接口实现
class Student implements Person {id: number;name: string;age: number;constructor(id: number,name: string, age: number) {this.id = id;this.name = name;this.age = age;}introduce(): void {console.log('Hello,I am a student');}}
class Teacher implements Person {id: number;name: string;age: number;constructor(id: number,name: string, age: number) {this.id = id;this.name = name;this.age = age;}introduce(): void {console.log('Hello,I am a Teacher');}}
然后分别创建一个Student对象和⼀个 Teacher 对象,注意两个对象的类型均可以设置Person ,如下:
let p1: Person = new Student(1, 'zhangsan', 17);
let p2: Person = new Teacher(2, 'list', 35)
p1.introduce(); //Hello, I am a student
p2.introduce(); //Hello, I am a teacher
接口的作用(重点!!!)
class Order {totalAmount: number;constructor(totalAmount: number) {this.totalAmount = totalAmount;} pay() {console.log(`AliPay: ${this.totalAmount}`);}}
interface PaymentStrategy {pay(amount: number): void;
}
class Order {totalAmount: number;paymentStrategy: PaymentStrategy;constructor(totalAmount: number,paymentStrategy: PaymentStrategy) {this.totalAmount = totalAmount;this.paymentStrategy = paymentStrategy; }pay() {this.paymentStrategy.pay(this.totalAmount);}}
这样改造完之后,就可以很容易的在不改变现有代码的情况下,支持新的支付方式了。
class AliPay implements PaymentStrategy {pay(amount: number): void {console.log(`AliPay:${amount}`);}
}
let order = new Order(1000,new AliPay());
order.pay();
稍等
就上面的代码我要讲一下。
this.paymentStrategy.pay(this.totalAmount) 是什么意思?
它就是利用当前订单对象所持有的支付策略对象来处理支付操作。使用策略模式的好处在于,可以将支付逻辑与订单对象的其他功能分离开来。
TS中的接口的特殊性
TypeScript中的接口是一个⾮常灵活的概念,除了⽤作类的规范之外,也常⽤于直接描述对象的类型,例如,现有⼀个变量的定义如下:
let person: {name:string, age:number, gender:string} = {name:'张三', age:10, gender:'男'};
interface Person {name: sting;age: number;gender: string;}let person: Person = {name:'张三', age:10, gender:'男'};