Overriding

Chapter: Overriding

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


Exercise 7

  1. Just to be sure it works, in your Exercise7 folder write RandomRect.java with this definition. Use the definitions of BasicShape and Rect shown above. Write RandomRectDemo.java that creates a random rectangle and then calls the repaint method of the current BasicShapesFrame 50 times (using a for loop). (Remember to use Thread.sleep after each repaint!)

  2. Now add to the RandomRect class new definitions for getX() and getY() that return random values between 0 and 300. When you run RandomRectDemo now, the rectangle will now both change color and position each time it is drawn.



rhyspj@gwu.edu