Dart基础语法<八> 类(中)

本节主要记录一下Dart中关于类的使用

  • Getters 和 Setters
  • 可覆写的操作符
  • 抽象类
  • 接口
Getters 和 Setters
  • Dart中每个实例变量都默认隐式配置了 getter, 如果变量非 final则还隐式设置了一个 setter。
  • 可以通过实现 getter 和 setter 创建新的属性, 使用 getset 关键字定义 getter 和 setter。
class Rect {
  int left;
  int right;
  int top;
  int bottom;

  int get width => right - left;

  int get height => bottom - top;

  Rect(this.left, this.right, this.top, this.bottom);
}

void main() {
  Rect rect = Rect(0, 10, 0, 10);
  print(rect.width);
  print(rect.height);
}
可覆写的操作符

即使用关键字operator 重新定义已有操作符的实现逻辑(如List就重写了 [])。以下是支持覆写的操作符:

< + | []
> / ^ []=
<= ~/ & ~
>= * << ==
% >>
import 'dart:math';

class Rect {
  int left;
  int right;
  int top;
  int bottom;

  int get width => right - left;

  int get height => bottom - top;

  Rect(this.left, this.right, this.top, this.bottom);

  Rect operator +(Rect rect) {
    int plusLeft = min(rect.left, left);
    int plusRight = max(rect.right, right);
    int plusTop = min(rect.top, top);
    int plusBottom = max(rect.bottom, bottom);
    return new Rect(plusLeft, plusRight, plusTop, plusBottom);
  }
}

void main() {
  Rect rect = Rect(0, 10, 0, 10);
  Rect plusRect = rect + Rect(20, 60, 10, 50);
  print(plusRect.width);
  print(plusRect.height);
}

如上述demo,覆写+操作符,定义生成两四边形最大的矩形区域。运行结果为宽度60 高度50

抽象类
  • Java一样,Dart修饰抽象类的关键字也是abstract
  • 抽象类允许出现无方法体的方法(即抽象方法),抽象方法无须使用abstract修饰。
abstract class Parent {
  String setupName();
  int setupAge();
}
  • 抽象类不能被实例化,但如果定义工厂构造方法可以返回子类。
abstract class Parent {
  String name;

  void showName();

  Parent(String name) {
    this.name = name;
  }

  factory Parent.son(String name) {
    return new Son(name);
  }
}

class Son extends Parent {
  Son(String name) : super(name);

  @override
  void showName() {
    print(name);
  }
}

void main() {
  Parent parent = new Parent.son("Juice");
  parent.showName();
}
接口
  • Dart中没有interface关键字,这点与Java不同。
  • Dart也是只支持单继承,但支持多实现。
  • Dart中每个类都隐式定义成接口。
class A {
  void printInfo() {
    print('A');
  }
}

class B implements A {
  @override
  void printInfo() {
    print('B');
  }
}

void main() {
  B b = B();
  b.printInfo();
}

运行结果为B

猜你喜欢

转载自blog.csdn.net/qq_22255311/article/details/112115425