Dart 面向对象编程语法

//*** Dart 面向对象编程语法  ***/

//类的很多语言和JAVA类似
//单一类继承、可继承多接口

class Point{
  //定义属性
  double x=0.0;
  double y=0.0;
  
  final String id;
  
  static const CLASS_NAME = "class<Point>";  //类的静态成员,属于类
  
  /* 构造函数相关
   * 没有构造函数,则自动指定默认构造函数,构造函数中调用父类构造函数
   * 
   */ 
  Point(this.id, this.x, this.y)
  {
    print("Point id= ${this.id}");
  }
  
  Point.origin(this.id, this.x, this.y) //命名式构造函数
  {
    print("Point id= ${this.id}");
  }
  
  //定义方法
  double getx() => x;
  double gety() => y;
  
  //静态方法,只能访问静态成员,只属于类的方法,不属于具体类的实例(同C++)
  static String getClassName()
  {
    return CLASS_NAME;
  }
}

//类的继承
class Vector extends Point{
  
  Vector(String id, double x, double y) : super(id,x,y)
  {
    print("Vector id= ${this.id}");
  }
  
  Vector.origin(String id, double x, double y) : super.origin(id, x, y) //命名式构造函数
  {
    print("Vector id= ${this.id}");
  }  
  
  //覆盖父类方法
  @override
  double getx() => x+1;
}

enum Color{red, green, blue} //枚举类型

void main()
{
  var p1 = Point('1', 1.0, 2.0);
  var p2 = Point.origin('2', 3.0, 4.0);
  
  var v1 = Vector('3', 1.0, 2.0);
  var v2 = Vector.origin('4', 3.0, 4.0);
  
  print("P:${p1.x}, ${p2.x}");
  print("V:${v1.x}, ${v2.x}");
  
  print("${p1.getx()}, ${v1.getx()}");
  
  print(Point.getClassName());
  
  print("Enum Color: ${Color.values}");
  print("Color red value: ${Color.red.index}");
}

 

posted @ 2021-06-23 13:48  前端人生  阅读(53)  评论(0编辑  收藏  举报