TS 学习五 类的继承与super,抽象类

类的继承

class Animal{
  name:string
  age:number

  constructor(name:string,age:number){
    this.name = name
    this.age = age
  }

  sing(jiao:string){
    console.log(jiao);
  }
}
/* 
定义一个狗的类
// dog1 继承 Animal 类
*/
class dog1 extends Animal{
}

/* 
定义一个猫的类
// cat 继承 Animal 类
*/
class cat1 extends Animal{

}


const dog2  = new dog1('小狗',2)
console.log(dog2);

const cat2 = new cat1('小猫',3)
console.log(cat2);

cat2.sing('喵喵喵')
cat2.sing('汪汪汪')


super,抽象类

/* 
以 abstract =>  抽象类
不能用来 创建 对象
抽象类 => 用来被继承的 类

抽象类 中 => 可以添加 抽象方法
*/
abstract class doing {
  food: string

  constructor(food: string) {
    this.food = food
  }

  // 定义一个抽象方法
  // 抽象方法使用 abstract 开头,没有方法体
  // 抽象方法 => 只能 定义在 抽象类 中,子类方法 必须对 父类方法 进行重写
  abstract eat():void
}

class toDoing extends doing {
  age: number

  constructor(age: number, name: string) {
    // 如果 在子类中, 写了 构造函数
    // 在子类的构造函数中,必须对父类的函数进行调用
    super(name) // => 调用父类的 构造函数
    this.age = age
  }

  eat() {
    // 在 类 的方法中,super 就表示 当前类的父类
    // super 引用 父类 方法
    // super.eat()

    console.log("我讨厌")
  }
}

const a = new toDoing(1, "面包")
console.log(a)
a.eat()

const b = new doing("热干面") // => 报错
console.log(b)
/* 
doing 以 abstract 开头=>  抽象类
不能用来 创建 对象
抽象类 => 用来被继承的 类
*/

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值