如果我有这样的代码,如何从子类中获取数据成员的值?

时间:2019-01-17 16:37:51

标签: oop dart

我还在学习flutter / dart语言教程。 这是我的代码。我创建了可以返回对象的方法。如何通过该方法从子类中获取数据成员。

abstract class Shape{
  get area;
}
class Circle implements Shape{
  final radius; 
  Circle(this.radius);

   get area=>pi*pow(radius,2);
}

class Square implements Shape{
  final side;
  Square(this.side);
  get area=>pow(side,2);
}

Shape shapeFactory(String type){
  if(type=='circle') return Circle(2);
  if(type=='square') return Square(2);
  throw 'Can\'t create $type.';

}

void main() {
  var s=shapeFactory('square');
  print(s.area);
  print(s.side);
  var c= shapeFactory('circle');
  print(c.area);
  print(c.radius);
}

如您所见,我可以获取面积值,但无法从类形状的子类的类圆或类正方形中获取半径或边值

1 个答案:

答案 0 :(得分:2)

这是因为Shape没有这些属性。您需要先强制转换为特定类型或使shapeFactory成为通用类型。

void main() {
  var s=shapeFactory('square') as Square;
  print(s.area);
  print(s.side);
  var c= shapeFactory('circle') as Circle;
  print(c.area);
  print(c.radius);
}

T shapeFactory<T extends Shape>(String type){
  if(type=='circle') return Circle(2) as T;
  if(type=='square') return Square(2) as T;
  throw 'Can\'t create $type.';
}

void main() {
  var s=shapeFactory<Square>('square');
  print(s.area);
  print(s.side);
  var c= shapeFactory<Circle>('circle');
  print(c.area);
  print(c.radius);
}