//接口: 通常情况下,接⼝中只会包含属性和⽅法的声明,⽽不包含具体的实现细节,具体的细节由其实现类完成
interface Person9 {
id: number;
name: string;
age: number;
introduce(): void;
}
//实现类中,需要包含接⼝属性的赋值逻辑,以及接⼝⽅法的实现逻辑
class Student9 implements Person9 {
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 Teacher9 implements Person9 {
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');
}
}
//多态:可以使同⼀类型的对象具有不同的⾏为
let p_1: Person9 = new Student9(1, 'zhangsan', 17);
let p_2: Person9 = new Teacher9(2, 'lisi', 35);
p_1.introduce(); //Hello,I am a student
p_2.introduce(); //Hello,I am a teacher
// 同样是 Person 类型的两个对象,调⽤同⼀个 introduce() ⽅法时,表现出了不同的⾏为,这就是多态
//TS中的接⼝的特殊性:TS中的接⼝是⼀个⾮常灵活的概念,除了⽤作类的规范之外,也常⽤于直接描述对象的类型
let P_345: {name:string, age:number, gender:string} = {
name:'张三',
age:10,
gender:'男'
};
console.log(P_345);
interface Person88 {
name: string;
age: number;
gender: string;
}
let P_678: Person88 = {
name:'张三',
age:10,
gender:'男'
};
console.log(P_678);