Dart是一门使用类和单继承的面向对象语言,所有的对象都是类的实例,并且所有的类都是Object的子类。
构造函数
// class Person{ // String name='张三'; // int age=20; // //默认构造函数 // Person(){ // print('这是构造函数里面的内容 这个方法在实例化的时候触发'); // } // void printInfo(){ // print("${this.name}----${this.age}"); // } // } // class Person{ // String name; // int age; // //默认构造函数 // Person(String name,int age){ // this.name=name; // this.age=age; // } // void printInfo(){ // print("${this.name}----${this.age}"); // } // } class Person{ String name; int age; //默认构造函数的简写,通常这么用 Person(this.name,this.age); void printInfo(){ print("${this.name}----${this.age}"); } } void main(){ Person p1=new Person('张三',20); p1.printInfo(); Person p2=new Person('李四',25); p2.printInfo(); }
区别1:与java的构造函数有点不同的是,dart里面构造函数可以写多个。
class Person{ String name; int age; //默认构造函数的简写 Person(this.name,this.age); Person.now(){ print('我是命名构造函数'); } Person.setInfo(String name,int age){ this.name=name; this.age=age; } void printInfo(){ print("${this.name}----${this.age}"); } } void main(){ // var d=new DateTime.now(); //实例化DateTime调用它的命名构造函数 // print(d); //Person p1=new Person('张三', 20); //默认实例化类的时候调用的是 默认构造函数 //Person p1=new Person.now(); //命名构造函数 Person p1=new Person.setInfo('李四',30); p1.printInfo();
}
区别2:Dart中没有 public private protected这些访问修饰符,但是我们可以使用_把一个属性或者方法定义成私有。
区别3:getter与setter修饰符
class Rect{ double height; double width; Rect(this.height,this.width); // getter修饰符 get area{ return this.height * this.width; } // setter修饰符 set areaHeight(value){ this.height = value; } } void main() { Rect r = Rect(10.0,5.0); print(r.area); r.areaHeight = 20.0; print(r.area); }
区别4:Dart可以在构造函数体运行之前初始化实例变量
class Rect{ int height; int width; Rect():height=2,width=10{ print("${this.height}---${this.width}"); } getArea(){ return this.height*this.width; } } void main(){ Rect r=new Rect(); print(r.getArea()); }
Dart中的静态成员与静态方法
class Person { static String name = '张三'; static void show() { print(name); } } void main() { print(Person.name); Person.show(); }
与java语法基本一样。
静态方法不能访问非静态成员,只能访问静态成员。
非静态方法可以访问非静态成员,也可以访问静态成员。
Dart中的对象操作符
条件运算符——?
class Person{ String name; int age; Person(this.name,this.age); void printInfo() { print("${this.name}---${this.age}"); } } void main() { Person p; p.printInfo(); // NoSuchMethodError: The method 'printInfo' was called on null. p?.printInfo(); // 如果p不为null时,执行printInfo方法。否则跳过。 }
类型转换(类似Java中的强制转换)——as
(p as Person).printInfo();
类型判断——is
if(p is Person){ ... }
级联操作——..
p..name = "李四" ..age = 30 ..printInfo();