Contributed by Leonardo
import std.stdio: writefln;
abstract class Shape {
private int x_, y_;
// constructor
this(int newx, int newy) {
this.x = newx;
this.y = newy;
}
// accessors for x & y coordinates
public int x() { return this.x_; }
public int y() { return this.y_; }
public void x(int newx) { this.x_ = newx; }
public void y(int newy) { this.y_ = newy; }
// move the x & y coordinates
public void moveTo(int newx, int newy) {
this.x = newx;
this.y = newy;
}
public void rMoveTo(int deltax, int deltay) {
moveTo(deltax + this.x, deltay + this.y);
}
// virtual routine - draw the shape
public void draw();
}
class Rectangle: Shape {
private int width_, height_;
// constructor
this(int newx, int newy, int newWidth, int newHeight) {
super(newx, newy);
this.width = newWidth;
this.height = newHeight;
}
// accessors for width & height
public int width() { return this.width_; }
public int height() { return this.height_; }
public void width(int newWidth) { this.width_ = newWidth; }
public void height(int newHeight) { this.height_ = newHeight; }
// draw the rectangle
public void draw() {
writefln("Drawing a Rectangle at:(%d,%d), Width %d, Height %d",
this.x, this.y, this.width, this.height);
}
}
class Circle: Shape {
private int radius_;
// constructor
this(int newx, int newy, int newRadius) {
super(newx, newy);
this.radius = newRadius;
}
// accessors for the radius
public int radius() { return this.radius_; }
public void radius(int newRadius) { this.radius_ = newRadius; }
// draw the circle
public void draw() {
writefln("Drawing a Circle at:(%d,%d), Radius %d", this.x, this.y, this.radius);
}
}
void main() {
Shape[] scribble;
// create some shape instances
scribble ~= new Rectangle(10, 20, 5, 6);
scribble ~= new Circle(15, 25, 8);
// iterate through the list and handle shapes polymorphically
foreach (shape; scribble) {
shape.draw();
shape.rMoveTo(100, 100);
shape.draw();
}
// call a rectangle specific function
auto rect = new Rectangle(0, 0, 15, 15);
rect.width = 30;
rect.draw();
}
Drawing a Rectangle at:(10,20), Width 5, Height 6 Drawing a Rectangle at:(110,120), Width 5, Height 6 Drawing a Circle at:(15,25), Radius 8 Drawing a Circle at:(115,125), Radius 8 Drawing a Rectangle at:(0,0), Width 30, Height 15