## 接口
接口是一种规范的定义,接口起到一种限制和规范的作用
- 对对象的形状进行描述和约束
// 首先对接口对象进行定义约束,指定类型,可以选定为只读类型(只可在初始化赋值),也可以添加可选参数,在属性名候添加问号
interface IPerson {
readonly id :number;
name:string;
isMale?:boolean;
}
let p1:IPerson = {
id:110,
name:'张三',
isMale:false
}
p1.id = 120; // error
类
概念:定义了一切事物的抽象特点。
三大特点:
1.封装:根据职责将属性和方法封装到一个抽象的类中
2.继承:实现代码的重用,相同的代码不需要重复的写
3.多态:(以封装和继承为前提),不同的子类对象调用相同的方法,产生不同的执行结果
下边是一个简单类的实现
class Animal {
name:string // 类的属性
constructor(name){
this.name = name
}
// 类的方法
run() {
return `${this.name} is Running`
}
}
const cat = new Animal('mimi')
console.log(cat.run());
- 修饰符
1.public为默认修饰符,可以在类内部,子类,类外面都可以访问
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
2.private为私有属性,它不能在声明它的类的外部访问,只能在内部访问
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; // 错误: 'name' 是私有的.
3.protected和private类似,不可以再类外部使用,但是可以在继承的子类中使用
class Animal {
protected name:string
constructor(name){
this.name = name
}
}
const dog = new Animal('wangcai');
console.log(dog.name); // error 不可以在外部访问
class Cat extends Animal{
constructor(name){
super(name)
console.log(name); // 继承父类的可以访问属性
}
}
const cat = new Cat('mimi')
4.static 静态属性,只可以被类本身调用
class Animal {
static introduce = 'We Are Animals'
}
console.log(Animal.introduce);
5.abstract抽象类,abstract关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。
abstract class Animal {
static introduce = 'We Are Animals'
abstract eat():string
}
class Dog extends Animal{
eat(){
return '子类实现父类抽象类'
}
}
类和接口
接口也可以对类进行抽象,在接口中只声明成员方法,在类中实现方法
在类后边加implements关键字实现接口方法
interface Run {
run(speed:string):string
}
class Dog implements Run
{
run(speed){
return `奔跑的速度为${speed}`
}
}