【ArkTS】implements详解
implements用于实现接口(interface)或抽象类,确保类满足特定的契约
包含implements子句的类必须实现列出的接口中定义的所有方法,但使用默认实现定义的方法除外。
单个接口:
interface DateInterface { now(): string; } class MyDate implements DateInterface { now(): string { // 在此实现 return 'now'; } }
多个接口:
// 定义多个接口 interface Flyable { fly(): void; maxAltitude: number; } interface Swimmable { swim(): void; maxDepth: number; } // 实现多个接口 class Duck implements Flyable, Swimmable { name: string; maxAltitude: number = 1000; // Flyable 接口要求 maxDepth: number = 10; // Swimmable 接口要求 constructor(name: string) { this.name = name; } fly(): void { console.log(`${this.name} is flying`); } swim(): void { console.log(`${this.name} is swimming`); } quack(): void { console.log("Quack quack!"); } } // 使用 const duck = new Duck("Donald"); duck.fly(); // Donald is flying duck.swim(); // Donald is swimming duck.quack(); // Quack quack!

浙公网安备 33010602011771号