#跟着坚果学鸿蒙#ArkTS 基础知识详解:类的继承
·
通过extends关键字实现类的继承,子类继承父类的字段和方法,并可新增或重写成员。
- 单继承规则
ArkTS 只支持单继承(一个子类只能继承一个父类)。
// 父类(基类)
class Shape {
color: string = "red";
draw(): void {
console.log(`Drawing ${this.color} shape`);
}
}
// 子类(派生类)
class Circle extends Shape {
radius: number;
constructor(radius: number) {
super(); // 子类构造函数必须首先调用父类构造函数
this.radius = radius;
}
}
- 方法重写(Override)
子类可重写父类的方法,需保证参数类型和返回类型兼容。
class Shape {
calculateArea(): number {
return 0; // 父类默认实现
}
}
class Rectangle extends Shape {
width: number;
height: number;
constructor(width: number, height: number) {
super();
this.width = width;
this.height = height;
}
calculateArea(): number { // 重写父类方法
return this.width * this.height;
}
}
- super关键字
用于访问父类的成员(字段、方法、构造函数)。
class Animal {
speak(): string {
return "Animal sound";
}
}
class Dog extends Animal {
speak(): string {
return super.speak() + " Woof!"; // 调用父类方法
}
}
const dog = new Dog();
console.log(dog.speak()); // 输出:Animal sound Woof!
更多推荐
所有评论(0)