我需要用Dart 2类来表示一张照片。照片可以是矩形的,也可以是圆形的。所以,通过多态性,我可以写:
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完成此操作?
谢谢!
发布于 2018-08-03 19:30:05
尝尝这个
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);
}发布于 2019-10-31 10:10:31
如果您来自java,那么下面的代码将看起来很熟悉。
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或任何其他您想要的实现。然后@重写照片类中的区域。
希望这会有帮助。
https://stackoverflow.com/questions/51677465
复制相似问题