ArkTS学习笔记:类的定义和对象的创建

文章目录

  • [1. 准备工作](#1. 准备工作)
  • [2. 类的定义](#2. 类的定义)
    • [2.1 语法格式](#2.1 语法格式)
    • [2.2 创建类](#2.2 创建类)
  • [3. 对象的创建](#3. 对象的创建)
    • [3.1 语法格式](#3.1 语法格式)
    • [3.2 创建对象](#3.2 创建对象)
  • [4. 运行程序,查看效果](#4. 运行程序,查看效果)
  • [5. 实战总结](#5. 实战总结)

1. 准备工作

  • 创建鸿蒙项目 - LearnArkTS
  • 编写首页代码
ts 复制代码
@Entry
@Component
struct Index {
  @State message: string = '学习ArkTS';

  build() {
    Column() {
      Text(this.message)
        .id('msg')
        .fontSize(30)
        .fontColor("red")
        .fontWeight(FontWeight.Bold)
        .margin(20)

      Button('运行')
        .fontColor(Color.Blue)
        .fontSize(30)
        .padding(10)
        .width(200)
        .margin(15)
        .backgroundColor('#44dd22')
        .foregroundColor('#ffffff')
        .onClick(() => {
          console.log(`欢迎你来${this.message}~`);
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .backgroundColor('222222')
  }
}
  • 启动应用,查看结果
  • 单击【运行】按钮,查看日志

2. 类的定义

2.1 语法格式

ts 复制代码
class 类名 {
    定义体 // 包含字段、构造函数、属性和方法
}
  • 在ArkTS中,类使用关键字class定义;class之后是类的名称,类名称必须是合法的标识符,建议使用大驼峰命名风格来命名;类名称之后是以一对花括号括起来的class定义体,class定义体中可以定义一系列类的成员,包括字段、构造函数、属性和方法。每定义一个类,就创建了一个新的自定义类型。

2.2 创建类

  • Index.ets中创建PhysicalEducation
ts 复制代码
class PhysicalEducation {
  readonly studentID: string; // 学号
  examScore: number; // 考试得分

  // 构造方法
  constructor(studentID: string, examScore: number) {
    this.studentID = studentID;
    this.examScore = examScore;
  }

  // 计算课程总评分
  calculateTotalScore(): number {
    return this.examScore
  }
}
  • 代码说明PhysicalEducation 类代表体育课,包含学号和考试得分属性。构造函数初始化这些属性,calculateTotalScore 方法返回学生的体育课总分,即考试得分。该类适用于管理和计算体育课成绩。

3. 对象的创建

3.1 语法格式

ts 复制代码
new 类名([参数列表]);
  • 在ArkTS中,使用new 类名([参数列表])语法创建类实例,初始化属性并调用构造函数。

3.2 创建对象

  • Index.ets里创建test()函数
ts 复制代码
function test() {
  const physicalEducation: PhysicalEducation = new PhysicalEducation('20240101', 90);

  // 访问实例字段
  console.log(`学号:${physicalEducation.studentID}`);
  console.log(`考试得分:${physicalEducation.examScore}`);

  // 调用实例方法
  console.log(`课程得分:${physicalEducation.calculateTotalScore()}`);
}
  • 代码说明 :这段代码演示了如何创建PhysicalEducation类的实例,并初始化学号和考试得分。然后,它访问并打印实例的属性值,最后调用calculateTotalScore方法来获取并打印课程总评分。

  • 在按钮的单击事件里调用test()函数

4. 运行程序,查看效果

  • 单击【运行】按钮,查看日志输出信息

5. 实战总结

  • 本次实战通过创建鸿蒙项目,学习了ArkTS的基本语法,包括类的定义、对象的创建和方法调用。通过编写首页代码,实现了一个简单的用户界面,并在按钮点击事件中测试了自定义类的实例化和方法调用,最终在日志中验证了输出结果。这个过程加深了对ArkTS面向对象编程的理解,并实践了如何在鸿蒙应用中操作UI组件和处理事件。
相关推荐
Huang兄6 天前
鸿蒙-List和Grid拖拽排序:仿微信小程序删除效果
harmonyos·arkts·arkui
Huang兄7 天前
鸿蒙-深色模式适配
harmonyos·arkts·arkui
西岸行者11 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
悠哉悠哉愿意11 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
别催小唐敲代码11 天前
嵌入式学习路线
学习
毛小茛11 天前
计算机系统概论——校验码
学习
babe小鑫11 天前
大专经济信息管理专业学习数据分析的必要性
学习·数据挖掘·数据分析
winfreedoms11 天前
ROS2知识大白话
笔记·学习·ros2
在这habit之下11 天前
Linux Virtual Server(LVS)学习总结
linux·学习·lvs
我想我不够好。11 天前
2026.2.25监控学习
学习