5.class类

封装,继承,多态

public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的
private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的3
readonly 只读

//封装
class Animal {
    public name: string;
    constructor(name: string) {
        this.name = name
    }
    run() {
        return `${this.name} is running`
    }
}

const snake = new Animal('lily') //实例化
console.log(snake.run());

//继承
class Dog extends Animal {
    bark() {
        return `${this.name} is barking`
    }
}
const xiaobao = new Dog('xiaobao')
console.log(xiaobao.run())
console.log(xiaobao.bark())
//多态
class Cat extends Animal {
    constructor(name: string) {
        super(name)
        console.log(this.name)
    }
    run() {
        return 'meow' + super.run()  //super.run() 调用父级方法
    }
}
const maomao = new Cat('maomao')
console.log(maomao.run())

你可能感兴趣的:(5.class类)