In one of the versions of BasicShape we put the operations on the position and color of a shape in the BasicShape class, because every shape has a position and a color. Here are the definitions of BasicShape and Rect that work this way:
BasicShape.java
import java.awt.*;
class BasicShape {
private Color col;
private int x, y;
public Color getColor() {return col;}
public void setColor(Color c) {col = c;}
public int getX() {return x;}
public void setX(int x1) {x = x1;}
public int getY() {return y;}
public void setY(int y1) {y = y1;}
public void paint(Graphics g) {}
}
Rect.java
import java.awt.*;
public class Rect extends BasicShape {
int wid, ht;
public Rect(int x, int y, int wid, int ht, Color col) {
setColor(col);
setX(x);
setY(y);
this.wid = wid;
this.ht = ht;
}
public void paint(Graphics g) {
g.setColor(getColor());
g.fillRect(getX(),getY(),wid,ht);
}
}
But some subclasses might want a different behavior for the position
and color operations. Suppose we want to introduce a type of
rectangle that appears in a different color, selected at random, each
time it is painted. Since we don't want all rectangles to have this
odd behavior, we derive a new class, RandomRect. Since RandomRect inherits the structure of Rect, we need only alter the
part that determines color; i.e. we must provide a new definition of
getColor(). We define RandomRect as follows. Again, we
only need to define the constructor and the new definition of getColor(). The rest is inherited from the definition of Rect.RandomRect.java
import java.awt.*;
public class RandomRect extends Rect {
public RandomRect(int x, int y, int wid, int ht, Color col) {
super(x,y,wid,ht,col);
}
public Color getColor() {
return new Color((int)(Math.random() * 256),
(int)(Math.random() * 256),
(int)(Math.random() * 256));
}
}