最简单的类
class Person { name: string //定义实例属性 age: number = 20 // 定义实例属性并且赋值 constructor(name: string) { this.name = name //实例属性赋值 } run(): void { console.log(this.name + 'is running'); } getName(): string { return this.name; } setName(name: string): void { this.name = name; } }
类继承extends|super
子类自动继承父类的所有实例属性和方法
父子都有的方法:子类只会调用自己的方法
子有父没有的方法:父亲不能子类扩展出来的方法
这里说明一下子类重写父类的方法细节:子类重写父类的方法的参数的个数和类型必须和父类保持一摸一样,当父类返回值类型是void,子类可以自定义返回值类型。一旦父类有规定的返回值类型。子类也必须是同样的返回值类型
其实也就是一句话:子类方法参数和返回值类型要包含(>=)父类方法的类型。但是参数数量要和父类保持一致性。
class Person { name: string age: number constructor(name: string, age: number) { this.name = name; this.age = age } showInfo(): void { console.log(this.name + this.age + '---'); } } class Student extends Person { gender: string // 如果子类不需要扩展自己的实例属性比如(gender)constructor构造函数可以省略不写,默认就继承了父类的实例属性和方法 constructor(name: string, age: number, gender: string) { super(name, age) this.gender = gender } showInfo() { console.log(this.name + this.age + this.gender); } sayHi(): void { console.log('hi'); } } const s = new Student('zs', 10, 'male') const p=new Person('zs',30) s.showInfo() //s是子类实例 子类有showInfo就去调用子类自己的 // p.sayHi() 父类是不能调用子类的实例方法
多态
实现多态的关键:子类继承并且重写父类的方法 并且父类型的引用指向子类型的对象
// 实现多态的关键:子类继承并且重写父类的方法 并且父类型的引用指向子类型的对象 let sam: Animal = new Snake("Sammy the Python"); sam.move() //注意 父子类都有move方法 但是是调用子类的move方法 let tom: Animal = new Horse("Tommy the Palomino") tom.move() //注意父子类都有move方法 是调用子类的move方法 interface IAnimal { (animal: Animal): void } let move: IAnimal = animal => { animal.move() } sam.move()
属性方式符
属性修饰符:可以修饰实例属性|方法 静态属性|方法
public:默认 当前类和子类和当前类实例和子类实例(实例也叫外部)都可以访问
protected:当前类和子类可以访问。当前类实例对象和子类实例对象都不能访问
private:只能在当前类种访问。不能再当前类实例和子类和子类实例对象访问
readonly
静态属性和方法
静态属性和方法 这些属性存在于类本身上面而不是类的实例上.换言之 静态属性、方法属于当前类,而不属于实例对象 静态方法的this是当前类本身。实例不能调用静态方法 静态属性和方法也是可以用关键字public|protected|private修饰的。于是也可以继承的
/**/ class Person { name: string; age: number constructor(name: string, age: number) { this.name = name this.age = age } public static sex: string = '男' //public可以省略 public static print(): void { // console.log(this); //this=Person this是当前类对象 // console.log(this.age); 访问不到实例对象属性 console.log(Person.sex); } run(): void { //实例方法 console.log(`${this.name} is run`); } } class Student extends Person { } const p = new Person('zs', 10) Person.print() //当前类.静态方法 const s = new Student('lisi', 20) Student.print() //子类.静态方法。前提是父类print方法用public修饰 console.log(Student.sex);
抽象类
抽象类和抽象方法用来定义标准的。抽象类作为其他派生类的基类使用,用abstract修饰。不能直接被实例化。
抽象方法必须定义在抽象类中,不能具体的实现且必须在派生类中实现,可以用属性修饰符修饰public|protected|private
abstract class Animal { abstract makeSound(): void move(): void { //抽象类里面也可以定义实例方法 这个实例方法可以被子类继承调用 console.log('moving'); } } class Dog extends Animal { makeSound(): string { // 子类必须实现抽象类方法,且不能改变抽象方法的入参 return '100' } } const dog: Dog = new Dog(); dog.move() dog.makeSound()