九、Dart的类
Dart属于OOP语言,因此满足OOP三大特性
Dart所有东西都是对象,所有对象都继承自Object类
Dart是一门使用类和单继承的面向对象语言,所有对象都是类的实例,并且所有的类都是Object的子类
一个类通常由属性和方法组成
定义一个类,并创建该类的实例,访问属性和方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Person{ String name = '张三' ; int age = 23; void getInfo(){ print( "${this.name}----${this.age}" ); } } void main(List<String> args) { Person person = new Person(); print(person.name); person.getInfo(); } |
类的默认构造函数(和JAVA一样)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Person{ String name = "" ; int age = 0; Person(String name, int age){ this .name = name; this .age = age; } void getInfo(){ print( "${this.name}----${this.age}" ); } } void main(List<String> args) { Person person = new Person( "张三" , 23); person.getInfo(); } |
构造函数简写
1 2 3 4 5 6 7 8 9 10 11 | class Person{ String name = "" ; int age = 0; Person( this .name, this .age); void getInfo(){ print( "${this.name}----${this.age}" ); } } |
类的命名构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Person{ String name = "" ; int age = 0; Person( this .name, this .age); Person.setInfo(String name, int age){ this .name = name; this .age = age; } void getInfo(){ print( "${this.name}----${this.age}" ); } } void main(List<String> args) { Person person = new Person.setInfo( "张三" , 23); person.getInfo(); } |
类的模块化
属性和方法的私有化
注意:属性和方法的私有化必须要将类单独抽离成一个文件
在属性名前面加入一个下划线即可让属性成为私有属性
在方法名前面加入一个下划线即可让方法成为私有方法
1 2 3 4 5 6 7 8 9 10 11 12 | class Person{ String _name; Person( this ._name); void _run(){} void getInfo(){ print( "${this._name}" ); } } |
get和set方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Person{ String _name = "" ; //set方法 set setName(name){ this ._name = name; } //get方法 get getName{ return this ._name; } void getInfo(){ print( "${this._name}" ); } } void main(List<String> args) { Person person = new Person(); //get、set方法在Dart中算是属性,所以使用属性的方式调用 person.setName= "张三" ; print(person.getName); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具