Dart中的私有方法 和私有属性

发布于 5 年前 作者 phonegap100 7742 次浏览 最后一次编辑是 3 年前 来自 分享

Dart Flutter免费教程https://www.itying.com/goods-1101.html

Dart和其他面向对象语言不一样,Data中没有 public private protected这些访问修饰符合

但是我们可以使用_把一个属性或者方法定义成私有。 Animal.dart

class Animal{
  String _name;   //私有属性
  int age; 
  //默认构造函数的简写
  Animal(this._name,this.age);

  void printInfo(){   
    print("${this._name}----${this.age}");
  }

  String getName(){ 
    return this._name;
  } 
  void _run(){
    print('这是一个私有方法');
  }

  execRun(){
    this._run();  //类里面方法的相互调用
  }
}

import 'lib/Animal.dart';

void main(){
 
 Animal a=new Animal('小狗', 3);

 print(a.getName());

  a.execRun();   //间接的调用私有方法
 

}
回到顶部