Contributed by Chris Rathman
include rMoveTo;
class Polymorph {
public static void main(String argv[]) {
Polymorph obj = new Polymorph();
}
Polymorph() {
// create some shape instances
Shape scribble[] = new Shape[2];
scribble[0] = new Rectangle(10, 20, 5, 6);
scribble[1] = new Circle(15, 25, 8);
// iterate through the list and handle shapes polymorphically
for (int i = 0; i < scribble.length; i++) {
draw(scribble[i]);
scribble[i].rMoveTo(100, 100);
draw(scribble[i]);
}
// call a rectangle specific function
Rectangle arect = new Rectangle(0, 0, 15, 15);
arect.setWidth(30);
draw(arect);
}
}
// draw - introduce method (internal)
void Polymorph.draw(Shape self) {}
// draw - dispatch on rectangle instance
void Polymorph.draw(Shape@Rectangle self) {
System.out.println("Drawing a Rectangle at:(" + self.getX() + ", " + self.getY() +
"), width " + self.getWidth() + ", height " + self.getHeight());
}
// draw - dispatch on circle instance
void Polymorph.draw(Shape@Circle self) {
System.out.println("Drawing a Circle at:(" + self.getX() + ", " + self.getY() +
"), radius " + self.getRadius());
}
|
abstract class Shape {
private int x;
private int y;
// constructor
Shape(int newx, int newy) {
moveTo(newx, newy);
}
// move the x & y position
void moveTo(int newx, int newy) {
setX(newx);
setY(newy);
}
// accessors for x & y
int getX() { return x; }
int getY() { return y; }
void setX(int newx) { x = newx; }
void setY(int newy) { y = newy; }
}
|
// Shape: introduce relative move method (external)
void Shape.rMoveTo(int deltax, int deltay) {
moveTo(getX() + deltax, getY() + deltay);
}
|
class Rectangle extends Shape {
private int width;
private int height;
// constructor
Rectangle(int newx, int newy, int newwidth, int newheight) {
super(newx, newy);
setWidth(newwidth);
setHeight(newheight);
}
// accessors for the width & height
int getWidth() { return width; }
int getHeight() { return height; }
void setWidth(int newwidth) { width = newwidth; }
void setHeight(int newheight) { height = newheight; }
}
|
class Circle extends Shape {
private int radius;
// constructor
Circle(int newx, int newy, int newradius) {
super(newx, newy);
setRadius(newradius);
}
// accessors for the radius
int getRadius() { return radius; }
void setRadius(int newradius) { radius = newradius; }
}
|
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 |