多态: 子类方法属性相同的前提下? || 子类方法属性不相同的前提下?

 多态:
     子类方法属性相同的前提下:子元素可以使用父元素的类而且各个子元素之间的类型也可以互相使用,这就是多态
     子类方法属性不相同的前提下:子元素可以使用父元素的类,但是子元素之间不能相互使用

export default function () {
    

    // 定义一个类
    class Animal<K> {
        name: K
        constructor(name: K) {
            this.name = name
        }
        run(distance = 15): K {
            return `${this.name}跑了${distance}公里` as unknown as K;
        }
    }

    class Dog<K> extends Animal<K>{
        constructor(name: K) {
            super(name);
        }
        run(distance = 15): K {
            return `${this.name}跑了${distance}公里` as unknown as K;
        }
        walk(item: K): K {
            return `小狗去玩了,${item}` as unknown as K;
        }
    }

    class Pig<K> extends Animal<K> {
        constructor(name: K) {
            super(name);
        }
        run(distance = 15): K {
            return `${this.name}跑了${distance}公里` as unknown as K;
        }
        sleep<T>(item: T): T {
            return `小狗去玩了,${item}` as unknown as T;
        }
    }


    // 实例化一个动物的类
    const animal: Animal<string> = new Animal<string>('动物');
    animal.run(20);
    const dog: Animal<string> = new Dog('哮天犬');
    dog.run(20);
    const pig: Pig<string> = new Pig('天蓬');
    pig.run(20);
    console.log(animal.run(20));
    console.log(dog.run(20));
    console.log(pig.run(20));
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值