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

2021-01-02  本文已影响0人  果汁味Studio

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

Getters 和 Setters
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

抽象类
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();
}
接口
class A {
  void printInfo() {
    print('A');
  }
}

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

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

运行结果为B

上一篇 下一篇

猜你喜欢

热点阅读