九、Dart的类

Dart属于OOP语言,因此满足OOP三大特性

Dart所有东西都是对象,所有对象都继承自Object类

Dart是一门使用类和单继承的面向对象语言,所有对象都是类的实例,并且所有的类都是Object的子类

一个类通常由属性和方法组成

 

定义一个类,并创建该类的实例,访问属性和方法

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一样)

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();
}

 构造函数简写

class Person{
  String name = "";
  int age = 0;

  Person(this.name,this.age);

  void getInfo(){
    print("${this.name}----${this.age}");
  }

}

  

类的命名构造函数

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();
}

  

类的模块化

 

 

 

 

属性和方法的私有化

注意:属性和方法的私有化必须要将类单独抽离成一个文件

在属性名前面加入一个下划线即可让属性成为私有属性

在方法名前面加入一个下划线即可让方法成为私有方法

class Person{
  String _name;

  Person(this._name);

  void _run(){}

  void getInfo(){
    print("${this._name}");
  }

}

  

get和set方法

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);
}

  

posted @ 2022-05-26 11:59  WaterGe  阅读(57)  评论(0编辑  收藏  举报