The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Drawable Rectangles

An an example of inheritance, we are going to take the existing Rectangle class and make it "drawable." That is, we are going to create a new class called DrawableRectangle that will have all the instance variables and methods of a Rectangle, plus an additional method called draw that will take a Graphics object as a parameter and draw the rectangle.

The class definition looks like this:

import java.awt.*;

class DrawableRectangle extends Rectangle {

  public void draw (Graphics g) {
    g.drawRect (x, y, width, height);
  }
}

Yes, that's really all there is in the whole class definition. The first line imports the java.awt package, which is where Rectangle and Graphics are defined.

The next line indicates that DrawableRectangle inherits from Rectangle. The keyword extends is used to identify the parent class.

The rest is the definition of the draw method, which refers to the instance variables x, y, width and height. It might seem odd to refer to instance variables that don't appear in this class definition, but remember that they are inherited from the parent class.

To create and draw a DrawableRectangle, you could use the following:

  public static void draw
           (Graphics g, int x, int y, int width, int height) {
    DrawableRectangle dr = new DrawableRectangle ();
    dr.x = 10;  dr.y = 10;
    dr.width = 200;  dr.height = 200;
    dr.draw (g);
  }

The parameters of draw are a Graphics object and the bounding box of the drawing area (not the coordinates of the rectangle).

It might seem odd to use the new command for a class that has no constructors. DrawableRectangle inherits the default constructor of its parent class, so there is no problem there.

We can set the instance variables of dr and invoke methods on it in the usual way. When we invoke draw, Java invokes the method we defined in DrawableRectangle. If we invoked grow or some other Rectangle method on dr, Java would know to use the method defined in the parent class.



Last Update: 2011-01-24