inheritance - 如何在 Dart 中扩展 Rectangle 类?

标签 inheritance dart

我想创建我的自定义矩形类,它是从 Rectangle 类扩展而来的。 我有一个错误,即类 Rectangle 没有声明性构造函数“Rectangle”,我已经看到 Rectangle 类的源代码并且有常量构造函数。 有可能做到吗?我认为可能的解决方案是使用组合而不是继承。感谢您的回答。

    part of Plot;

    class PlotRectangle extends Rectangle{

      // Rectangle<int> rectangle; // as variant use composition
      String color = "red"; 

      PlotRectangle(int left, int top, int width, int height): super.Rectangle(left, top, width, height){

      }

      PlotRectangle.withColor(int left, int top, int width, int height, this.color): super.Rectangle(left, top, width, height){
        this.color = color;
      }

      void setColor(String color){
        this.color = color;
      }  
    }

最佳答案

尝试了一下,成功了

library x;

import 'dart:math';

class PlotRectangle<T extends num> extends Rectangle<T> {
  PlotRectangle(T left, T top, T width, T height) : super(left, top, width, height);

  String color = 'red';

  factory PlotRectangle.fromPoints(Point<T> a, Point<T> b) {
    T left = min(a.x, b.x);
    T width = max(a.x, b.x) - left;
    T top = min(a.y, b.y);
    T height = max(a.y, b.y) - top;
    return new PlotRectangle<T>(left, top, width, height);
  }

  PlotRectangle.withColor(T left, T top, T width, T height, this.color) : super(left, top, width, height);

  @override
  String toString() => '${super.toString()}, $color';
}

void main(List<String> args) {
  var r = new PlotRectangle(17, 50, 30, 28);
  print(r);
  var rc = new PlotRectangle.withColor(17, 50, 30, 28, 'blue');
  print(rc);
}

关于inheritance - 如何在 Dart 中扩展 Rectangle 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21511886/

相关文章:

C++ 重写虚拟模板方法

dart - 局部变量的问题 - 全局变量 flutter dart

c# - 覆盖时是否必须调用基本实现?

c++ - 访客 : adding more types via inheritance

python - 可以从现有日期时间实例创建的自定义日期时间子类?

dart - 关于DART for Java Equivalent,等效类/基元是什么?

bash - WSL 和 bash 命令

java - Class<T extends AnotherClass> 方法泛型

flutter - 在 url_launcher mailto 方案中,空格被转换为 + flutter

flutter - 在Google map 上快速显示多个标记