1.三大特征:
封装:封装成抽象的类,提供部分属性和方法
继承:面向对象编程OOP主要功能,使用现有类的功能
多态:子类类型的指针赋值赋值给父类,调用同一个函数,会有不同结果
2.类
Dart 所有东西都是对象,均来自Object类,
Dart是单继承语言
一个类通常由属性和方法组成
构造函数:实例化类时自动调用的方法
class Person{
//String name="李白";
String name="";
//int age =28;
int age=0;
void getInfo(){
//print("$name---$age");
//print("${this.name}------${this.age}");//推荐写法
}
void setInfo(int age2){
this.age=age2;
}
//构造函数,要与类名相同,实例化类时候自动执行
没内容甚至可以不写{}
// Person(){
// print("我是构造函数");
// }
Person(String name1,int a1){
this.name=name1;
this.age=a1;
}
}
void main(List<String> args) {
//实例化
var p1=new Person("杜甫",33);//or Person p1=new Person();
print(p1.name);
var p2=new Person("李白",43);//or Person p1=new Person();
print(p2.name);
}
3.修飾符
没有public private protected
在变量前加_,但是同一个文件永远可以使用,实际上是名称变了,变成_name
间接获取
String getName(){
return this._name;
}
访问私有方法
execRun(){
this._run();
}
4.get set属性:调用不需要()很少用
class Rect{
num height;
num width;
Rect(this.height,this.width);
get area{//系统提供get,不用()的方法 计算属性
return this.height*this.width;
}
set areaHeight(value){ //系统tigongget属性,调用不需要()
this.height=value;
}
}
void main(List<String> args) {
Rect r=new Rect(40, 20);
print("面积:${r.area}");
r.areaHeight=90;
}
初始化函数:很少用
num height;
num width;
Rect():height=2,width=10{} //构造前赋值
getArea(){
return this.height*this.width;
}
}
void main(List<String> args) {
Rect r=new Rect();
print(r.getArea());
}
本文主要介绍了Dart语言面向对象编程的相关知识。阐述了封装、继承、多态三大特征,说明了类的组成、构造函数的使用,还提及了修饰符、get set属性及初始化函数等内容,并给出了相应的代码示例。
1098

被折叠的 条评论
为什么被折叠?



