Marco
Marco

Reputation: 593

Dart 2 class with a constructor very similar to the polymorphism of other languages

I need to represent a photo with a Dart 2 class. The photo can be rectangular or circular. So, with a polymorphism I could write:

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

So I could allow to create a Photo with radius or a Photo with width and height; no other option.

How can I do this with Dart 2?

Thanks!

Upvotes: 2

Views: 804

Answers (2)

Kshitij Dhakal
Kshitij Dhakal

Reputation: 844

If you are coming from java, then following code will look familiar.

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

You create abstract photo class with radius only (since length and height are specific to RectPhoto and radius is specific to CircularPhoto). Then create RectPhoto, CircularPhoto or any other implementation you'd like. Then @override area from Photo class.

Hope this is helpful.

Upvotes: 1

Kevin Moore
Kevin Moore

Reputation: 6161

Try this

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

Upvotes: 1

Related Questions