Dart--03--类和对象
2022-04-06 本文已影响0人
XieHenry
前言:
面向对象编程(OOP)的三个基本特征是:封装、继承、多态
封装:封装是对象和类概念的主要特性。封装,把客观事物封装成抽象的类,并且把自己的部分属性和方法提供给其他对象调用, 而一部分属性和方法则隐藏。
继承:面向对象编程 (OOP) 语言的一个主要功能就是“继承”。继承是指这样一种能力:它可以使用现有类的功能,并在无需重新编写原来的类的情况下对这些功能进行扩展。
多态:允许将子类类型的指针赋值给父类类型的指针, 同一个函数调用会有不同的执行效果 。
Dart
是一门使用类和单继承的面向对象语言,所有的对象都是类的实例,并且所有的类都是Object的子类
1.定义一个类
//定义一个类
class Person {
String name = "xiehenry"; //定义的属性
int age = 27;
void getInfo() {
print("${this.name}----${this.age}");
}
void setInfo(int age) {
this.age = age;
}
}
//main函数内调用
var p1=new Person();
print(p1.name);
p1.getInfo();
2.默认构造函数,命名构造函数
class Person{
String name;
String _height; //私有属性
int age;
//默认构造函数-不需要调用,就会自动执行,可以简写为下面的代码
Person(String name,int age){
this.name=name;
this.age=age;
}
//默认构造函数的简写
//Person(this.name,this.age);
Person.now(){ //可以有多个命名构造函数
print('我是命名构造函数');
}
void _run(){
print('这是一个私有方法');
}
execRun(){ //可以通过这个方法调用私有的 _run方法
this._run(); //类里面方法的相互调用
}
void printInfo(){
print("${this.name}----${this.age}");
}
}
//调用
Person p1=new Person('张三', 20); //默认实例化类的时候调用的是 默认构造函数
Person p2=new Person.now(); //命名构造函数
p2.execRun();//间接调用私有方法
3.类的getter和setter方法
class Rect{
num height;
num width;
Rect(this.height,this.width);
get area{
return this.height*this.width;
}
set areaHeight(value){
this.height=value;
}
}
//main函数调用
Rect r = new Rect(10, 4);
// print("面积:${r.area()}"); //40
r.areaHeight = 6;
print(r.area);//24
4.类中的初始化列表
class Rect {
int height;
int width;
Rect(): height = 2,width = 10 {// Dart中我们也可以在构造函数体运行之前初始化实例变量
print("${this.height}---${this.width}");
}
getArea() {
return this.height * this.width;
}
}
//main函数中调用
Rect r = new Rect();
print(r.getArea());