Dart 类

2021-04-20  本文已影响0人  逍遥德道

//不可变

class ImmutabelPoint {

  final int x;

  final int y;

  //常量构造方法

  const ImmutabelPoint(this.x, this.y);

}

class Point {

  //使用 _ 是私有的

  int _x;

  int y;

  //方法不能重载

  Point(this._x, this.y);

  //命名构造方法

  Point.X(this._x);

  //参数初始化列表使用 :

  Point.fromMap(Map map)

      : _x = map["x"],

        y = map["y"];

  //这个跟kotlin 一样

  Point.from() : this(1, 1);

}

class _P {}

void main(){

  main2();

}

void main1() {

  // var p = Point(1,1);

  // p.y;

  //使用的const 创建的对象,传递的参数也一样,是同一个对象

  var p1 = const ImmutabelPoint(1, 1);

  var p2 = const ImmutabelPoint(1, 1);

  print(p1 == p2);

  print(p1.hashCode == p2.hashCode);

}

//工厂构造方法 加 单例实现

class Manager {

  static Manager _instance;

  factory Manager.getInstance() {

    _instance ??= Manager._newInstance();

    return _instance;

  }

  //static 表现与 factory一样 但是返回值要确定 Manager

  static Manager get() {

    return Manager._newInstance();

  }

  //这样不能实现单例

  // Manager();

  //使用命名构造方法 加 _ 的形式构造私有构造方法

  Manager._newInstance();

}

//get set

class getSet {

  int _x;

  int y;

  //因为有隐形 get x ,不能进行重写

  // int get x =>x + 10;

  //只能通过这种转换的方式进行

  int get x => _x;

  set x(int x) => _x = x;

  int get yy => y;

  set yy(int yy) => y = yy;

}

//操作符重载

class Operators {

  int x;

  int y;

  //返回值,随意

  Operators operator +(Operators operator) {

    var op = Operators();

    op.x = x + operator.x;

    op.y = y + operator.y;

    return op;

  }

  String operator -(String string) {

    return "";

  }

}

//抽象类

abstract class Parent {

  void parent(); //抽象方法不能写 abstract

}

//单继承,所有的类都可以是接口,进行实现

class Child extends Parent {

  @override

  void parent() {}

}

//实现

class Child2 implements Child {

  @override

  void parent() {}

  //可以使用  Child2 child = Child2();

  // child() == child.call();

  void call() {}

}

//混合 mixin

void main2() {

  var c = C();

  //这个方法是哪个类的呢

  //从后往前找  B,A

  c.a();

  c.b();

  //先找自己的,找不到后,从后往前找

  //混入类时,先混入A的所有方法,再混入B的方法的时把与A重合的方法顶替了

  c.c();

}

//被混入的类不能有构造方法

class A {

  void a() {}

  void c(){

    print("A 中的 C 方法");

  }

}

class B {

  void a(){}

  void b() {}

  void c(){

    print("B 中的 C 方法");

  }

}

class C with A, B {

  //重写了B中的c()方法

  void c() {

    super.c();

    print("C 中的 C 方法");

  }

}

//混合 D没有自己的方法与属性

class D = Object with A, B;

上一篇 下一篇

猜你喜欢

热点阅读