鸿蒙Harmony OS Next原生开发TS的类的继承与实际开发中的应用

鸿蒙初开,开天辟地

类的继承和实际开发中的应用

和很多面向对象编程的语言OOP一样,我们使用类都是为了在原有的基础上拓展和使用更多的属性和功能

class Control{
  version:number;
  control:string;
  constructor(version:number,control:string){
    this.version = version;
    this.control = control;
  }
  helloWorld(){
    console.log(this.version,this.control);
  }
}
class cShape extends Control{
  java:string;
  constructor(version:number,control:string,java:string){
    super(version,control);
    this.java = java;
  }
  javaWorld(){
    console.log(this.java);
  }
}
let java:Control = new cShape(1.8,"javac","springBoot");
java.helloWorld();

使用拓展了属性和方法的子类

在这里,我们通过将继承了父类的子类声明为一个父类的对象,使得我们可以拥有一个功能和属性强于父类的父类对象

这意味着,这个被声明为父类的实际为子类的对象同时拥有了父类和子类所有的属性和方法

因此,当我们重写父类原本的方法时,调用的方法就是之类的方法了

class Control{
  version:number;
  control:string;
  constructor(version:number,control:string){
    this.version = version;
    this.control = control;
  }
  helloWorld(){
    console.log(this.version,this.control);
  }
}
class cShape extends Control{
  java:string;
  constructor(version:number,control:string,java:string){
    super(version,control);
    this.java = java;
  }
  helloWorld(){
    console.log(this.java);
  }
  javaWorld(){
    console.log(this.java);
  }
}
let java:Control = new cShape(1.8,"javac","springBoot");
java.helloWorld();

尽管还是一个父类对象,但是已经拥有了子类的方法和属性

 本质上就是一个声明为父类的对象指针实际上指向的是一个子类对象

class Control{
  version:number;
  control:string;
  constructor(version:number,control:string){
    this.version = version;
    this.control = control;
  }
  helloWorld(){
    console.log(this.version,this.control);
  }
}
class cShape extends Control{
  java:string;
  constructor(version:number,control:string,java:string){
    super(version,control);
    this.java = java;
  }
  helloWorld(){
    super.helloWorld();
    console.log(this.java);
  }
  javaWorld(){
    console.log(this.java);
  }
}
let java:Control = new cShape(1.8,"javac","springBoot");
java.helloWorld();

通过super使用父类已经被覆盖重写掉的方法

在这里我们通过super就又可以使用父类本身被覆盖掉的同名方法了,这就大大拓展了我们这个新的"父类对象"的功能和属性 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值