首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dart 2类的构造函数与其他语言的多态非常相似。

Dart 2类的构造函数与其他语言的多态非常相似。
EN

Stack Overflow用户
提问于 2018-08-03 17:26:35
回答 2查看 753关注 0票数 2

我需要用Dart 2类来表示一张照片。照片可以是矩形的,也可以是圆形的。所以,通过多态性,我可以写:

代码语言:javascript
复制
import 'dart:math';

class Photo {
  double width;
  double height;
  double radius;
  double area;

  Photo(double width, double height) {
    this.width = width;
    this.height = height;
    this.area = width * height;
  }

  Photo(double radius) {
    this.radius = radius;
    this.area = pi * pow(radius, 2);
  }
}

因此,我可以允许创建一个半径的照片或宽度和高度的照片;,而不是其他选项

如何使用Dart 2完成此操作?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-03 19:30:05

尝尝这个

代码语言:javascript
复制
import 'dart:math';

class Photo {
  final double area;

  // This constructor is library-private. So no other code can extend
  // from this class.
  Photo._(this.area);

  // These factories aren't needed – but might be nice
  factory Photo.rect(double width, double height) => new RectPhoto(width, height);
  factory Photo.circle(double radius) => new CirclePhoto(radius);
}

class CirclePhoto extends Photo {
  final double radius;

  CirclePhoto(this.radius) : super._(pi * pow(radius, 2));
}

class RectPhoto extends Photo {
  final double width, height;

  RectPhoto(this.width, this.height): super._(width * height);
}
票数 1
EN

Stack Overflow用户

发布于 2019-10-31 10:10:31

如果您来自java,那么下面的代码将看起来很熟悉。

代码语言:javascript
复制
import 'dart:math';

abstract class Photo {
  double area();
}

class CircularPhoto extends Photo {
  double radius;

  CircularPhoto(this.radius);

  @override
  double area() {
    return pi * pow(this.radius, 2);
  }
}

class RectPhoto extends Photo {
  double length;
  double height;

  RectPhoto(this.length, this.height);

  @override
  double area() {
    return this.length * this.height;
  }
}

void main(){
  Photo p = new CircularPhoto(5);
  print(p.area());
}

只使用radius创建抽象的CircularPhoto).照片类(因为长度、高度是特定于RectPhoto的,而radius是特定于的)。然后创建RectPhoto、RectPhoto或任何其他您想要的实现。然后@重写照片类中的区域。

希望这会有帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51677465

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档