【问题标题】:How to extend Rectangle class in Dart?如何在 Dart 中扩展 Rectangle 类?
【发布时间】:2014-02-02 14:45:20
【问题描述】:

我想创建从 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;
      }  
    }

【问题讨论】:

    标签: inheritance dart


    【解决方案1】:

    试过了,效果很好

    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);
    }
    

    【讨论】:

      【解决方案2】:

      正如 Günter 已经表明的那样,这是很有可能的。

      更具体一点,代码中的错误是对超级构造函数的调用:

      super.Rectangle(left, top, width, height) 应该是super(left, top, width, height)

      您的语法尝试调用命名构造函数“Rectangle”,这相当于new Rectangle.Rectangle - 该构造函数不存在。您想调用“普通”构造函数 (new Rectangle),只需使用 super 即可调用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-22
        • 2020-02-06
        • 2013-04-21
        • 2013-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多