ArkTS的类,接口

ArkTS的类,接口

一、类

1. 基本的定义和实例化

相关概念:

  • 字段:可以理解为在类里面定义的成员变量,分为静态字段和实例字段

  • 方法:在类里面定义的函数,但是不要把构造函数也归纳到这个里面

  • 构造函数:construct( ) 是一个用来对类里面的成员实例(字段)进行快捷赋值的函数方法,在实例化对象时自动触发,

示例:

class Animal{
	//定义字段,即成员变量
	name: string
	color: string
	age: number
	static version: string = '1.0'
	
	//构造函数,不允许其别的名字,这个是固定的
	constructor(name: string, color: string, age: number){
		this.name = name
		this.color = color
		this.age = age
	}
	
	//定义方法,即成员方法
	getColor(){
		return this.color;
	}
}

let cat: Animal = new Animal('猫', '白色', 1)
console.log(cat.name,cat.color,cat.age)	   //输出:猫 白色 1
console.log('猫的颜色是', cat.getColor())	//输出:猫的颜色是 白色

2. 类的继承

类与类之间的继承靠的是 extends 来继承

子类调用父类的构造函数是靠super来使用

子类要是想重写父类的方法,只需要方法名相同就可以

class Animal {
  name: string;
  age: number;
  static version: string = '1.0';

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

class Cat extends Animal {
  color: string;
  voice: string;

  constructor(name: string, color: string, age: number, voice: string) {
    super(name, age);		// 只用于构造函数当中
    this.color = color;
    this.voice = voice;
  }
}

let cat: Cat = new Cat('猫', '黑色', 5, '喵');
console.log(cat.name, cat.color, cat.age, cat.voice, Animal.version);	// 输出:猫 黑色 5 喵 1.0

3. 类的修饰符

用来限制对类的成员的访问权限

与其他语言不同的是,ArkTS提供了四个限制

readonly(只读不可改),private(私有的),protected(受保护的),public(公有的)

示例:

class Person {
  readonly version: string = '1.0';
  private country: string;
  name: string;
  age: number;

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

  getCountry() {
    return this.country
  }
}

let person: Person = new Person('小明', 18, '中国人')
// person.version = '1.1'  // 报错,只读变量不能修改
console.log(person.name, person.age, person.version)
// console.log(person.country)  // 报错,私有变量外部不可以通过 . 来访问
console.log('他的国家是', person.getCountry())

4. 静态属性和方法

使用static关键字定义

class MathUtil {
    static PI: number = 3.14;

    static areaOfCircle(radius: number): number {
        return MathUtil.PI * radius * radius;
    }
}

console.log(MathUtil.PI); // 输出: 3.14
console.log(MathUtil.areaOfCircle(5)); // 输出: 78.5

I.静态变量

局部静态变量:作用于函数内部,但生命周期为整个程序执行期间。

全局静态变量:作用于定义它的文件,其他文件无法访问。

他们的值,在没有使用const定义时,可以被修改

II.静态函数

只能在定义它的文件中使用,其他文件无法调用,帮助封装实现细节。

二、接口

使用interface来定义,与类有点相似,只是接口更多的是更抽象的东西,只是定义了成员的类型相关的

1. 简单定义

//定义接口
interface Person{
	name: string;
	age: number;
	weight: number;
}

//定义对象
let xh: Person = {
	name: 'xiaohong',
	age: 18,
	weight: 90
}

从上面例子可以看出,接口的定义其实就类似于创建了一个数据类型,用它来规范一个对象的内容。

注:

接口里面用的是 ; 对象里面用的是 ,

2. 接口的继承和实例化

I. 接口的继承采用的是extend

II. 接口的实现,也就是靠类来实现接口用的是implements

示例:

interface Style {
  color: string
}

// 继承接口包含被继承接口的所有属性和方法
// 还可以添加自己的属性和方法。
interface Area extends Style {
  width: number
  height: number

  // 方法的声明
  someMethod(): void;
  // someMethod: () => void; //也可以这样定义
}

class Rectangle implements Area {
  // 可以新增属性,但是接口的属性必须实现
  // 1.接口属性通过直接声明实现
  width: number;
  height: number;
  // 2.接口属性通过getter、setter方法实现,等价于上面方法1
  private _color: string = ''

  constructor(width:number, height: number) {
    this.width = width
    this.height = height
  }
  get color(): string {
    return this._color
  }

  set color(x: string) {
    this._color = x
  }

  // 接口方法实现
  someMethod(): void {
    console.log('someMethod called')
  }
}

const rectangle = new Rectangle(20,)
rectangle.someMethod()
### 如何在 ArkTS 中定义 #### 的基本结构 在 ArkTS 中,`class` 关键字用于定义一个新的。一个典型的包含属性和方法。以下是定义的基础语法: ```typescript class MyClass { // 属性声明 property: string; // 构造函数 constructor(propertyValue: string) { this.property = propertyValue; } // 方法定义 myMethod(): void { console.log(`Property value is ${this.property}`); } } ``` 在此基础上可以进一步扩展的功能[^1]。 #### 使用 `static` 定义静态成员 为了使某些属性或方法属于整个而不是特定的对象实例,在 ArkTS 中可以通过添加 `static` 关键字来实现这一点: ```typescript class StaticExample { static staticProperty: number = 0; static incrementStaticProperty(): void { StaticExample.staticProperty++; } } // 调用静态方法并访问静态属性 StaticExample.incrementStaticProperty(); console.log(StaticExample.staticProperty); // 输出:1 ``` 此中的 `staticProperty` 和 `incrementStaticProperty()` 都是静态成员,可以直接通过名调用来使用它们。 #### 继承机制 当希望新创建的能够继承已有的行为时,则可以在定义子的时候指定父作为其基底,并利用 `super()` 来初始化父构造器传递必要的参数给它: ```typescript class BaseClass { baseProperty: string; constructor(basePropertyValue: string) { this.baseProperty = basePropertyValue; } getBaseMessage(): string { return "This message comes from the base class."; } } class DerivedClass extends BaseClass { derivedProperty: string; constructor(basePropVal: string, derivedPropVal: string) { super(basePropVal); this.derivedProperty = derivedPropVal; } getDerivedMessage(): string { return `${this.getBaseMessage()} And here's an additional message.`; } } const instanceOfDerived = new DerivedClass('base', 'derived'); console.log(instanceOfDerived.getDerivedMessage()); ``` 这段代码展示了如何让 `DerivedClass` 继承自 `BaseClass`, 同时也实现了自己的特有行为. #### 接口支持 对于更复杂的场景来说,可能还需要考虑接口的支持。接口允许开发者描述对象应该具有哪些属性以及这些属性的数据型;另外也可以为接口增加具体的方法签名以便于后续的具体实现遵循此契约: ```typescript interface MyInterface { requiredProperty: boolean; optionalProperty?: number; methodOne(param: any): void; } class InterfaceImplementer implements MyInterface { requiredProperty = true; optionalProperty = 42; methodOne(_param: any): void { console.log("Implemented method one."); } } ``` 这里展示的是怎样基于接口去构建具体的实现.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alfredorw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值