ts13_继承

(function () {
    //定义一个dog类
    class Animal {
        name: string;
        age: number;
        constructor(name: string, age: number) {
            this.name = name;
            this.age = age;

        }
        sayhello() {
            console.log("动物在叫---");

        }
    }
    class Dog extends Animal {//使Dog类继承自Animal类,此时Animal被称为父类,Dog被称为子类
        //使用继承后子类会拥有父类的所有方法和属性
        //通过继承可以将多个类中共有的代码放在一个父类中
        //这样只需要写一次代码就能让所有子类中同时有父类中的代码
        //如果希望在子类中增加父类中没有的的属性或者方法直接添加即可
        //如果在子类中添加了和父类相同的方法则子类方法会覆盖掉父类的方法(不会改变父类,只会改子类中的方法)
        //这种子类覆盖掉父类方法的形式称为方法的重写
        sayhello(): void {
            console.log('汪汪汪')
        }
        run() {
            console.log(`${this.name}在跑`)
        }

    }
    class Cat extends Animal {//使Cat类继承自Animal类,此时Animal被称为父类,Cat被称为子类
        sayhello(): void {
            console.log('喵喵喵')
        }

    }
    const dog1 = new Dog('旺财', 2)
    console.log(dog1);
    dog1.run()
    dog1.sayhello()
    const cat1 = new Cat("咪咪", 2)
    console.log(cat1);

    cat1.sayhello()
    console.log(Animal)
})()

 

posted @ 2022-12-26 15:27  SadicZhou  阅读(18)  评论(0编辑  收藏  举报