鸿蒙初开,开天辟地
类的继承和实际开发中的应用
和很多面向对象编程的语言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就又可以使用父类本身被覆盖掉的同名方法了,这就大大拓展了我们这个新的"父类对象"的功能和属性