Dart语言零基础学习笔记(十三)
dart中没有私有访问修饰符,只能在属性或者方法前加上下划线来定义成私有
私有方法和私有属性需要单独抽离到一个文件里
Dart中的私有属性
在属性前加上下划线来定义成私有 var _name;
class Cat {
var age;
var _name;
Cat(this._name, this.age);
printInfo() {
print("$_name is $age years old;");
}
}
此时,在main文件里面是无法访问name的。
但是私有属性可以通过公有的方法来访问
私有属性可以在当前类里面使用,通过访问公有方法来间接访问私有属性
cat.dart
class Cat {
var age;
var _name;
Cat(this._name, this.age);
getName() {
return this._name;
}
printInfo() {
print("$_name is $age years old;");
}
}
main.dart
import 'cat.dart';
void main(List<String> args) {
var cat = new Cat("小花", 3);
//cat._name;//_name是私有属性,无法访问
/*通过访问公有方法getName来间接访问私有属性_name*/
print(cat.getName());//小花
print(cat.age);//3
cat.printInfo();//小花 is 3 years old;
}
Dart中的私有方法
在方法前加上下划线来定义成私有 var _print;
此时,在main文件里面是无法访问_print
但是私有方法可以通过公有的方法来访问
私有属性可以在当前类里面使用,通过访问公有方法来间接访问私有方法
cat.dart
class Cat {
var age;
var _name;
Cat(this._name, this.age);
_print() {
//私有方法
print("this is a siyou fangfa");
}
getSiyou() {
return this._name;
}
printInfo() {
print("$_name is $age years old;");
}
}
main.dart
import 'cat.dart';
void main(List<String> args) {
var cat = new Cat("小花", 3);
cat.getSiyou();//this is a siyou fangfa
}
get修饰符
class Rect {
var height;
var wight;
Rect(this.height, this.wight);
// area() {
// return this.height * this.wight;
// }
get area {
return this.height * this.wight;
}
}
void main(List<String> args) {
Rect r = new Rect(5, 2);
print('面积:${r.area}'); //调用直接通过访问属性的方式来访问are
}
set修饰符
class Rect {
var height;
var wight;
Rect(this.height, this.wight);
area() {
return this.height * this.wight;
}
set areahight(Value) {
this.height = Value;
}
}
void main(List<String> args) {
Rect r = new Rect(5, 2);
r.areahight = 1;
r.area();
print(r.area());//2
}
类中的初始化列表
class Rect {
var height;
var wight;
//Rect(this.height, this.wight);
Rect():height=10,wight=2{
}
area() {
return this.height * this.wight;
}
}
void main(List<String> args) {
Rect r = new Rect();
print(r.area());//20
}