Concurrent Programming with Java
Lab Manual, Version 1.0, F. Astha Ekadiyanto, 2002.

[Contents] [Next] [Previous]

Lab 3: Building Applets - Graphical representation


Adding draw(Graphics) method in Cell Classes

When adding new non private methods in subClasses, be very careful because these methods may not be recognized by other Objects. For example, in the Rbs Class, the field that cellAssigned is by signature, defined as a Cell Class reference (not SquareCell or others, although it is intended to store one of them). This means, whenever a Cell or corresponding subCell method is called using the cellAssigned reference, the compiler will check whether the method is defined in the Cell Class (which is probably not exist for draw(Graphics)).

Example: System.out.println( "" + cellAssigned.area() );

The code above will print out the area of the Cell object refered by cellAssigned field. If the object is a SquareCell, then it will print the area calculated using a SquareCell function. If the object is a HexCell, then the corresponding HexCell area function is used.

Thus, there are two ways to modify Cell's SubClasses so that any different SubClass of Cell will be treated equally by accessing objects:

We will try the second solution by building an Interface that we call Visualization and define the draw(Graphics) method's signature:

File name: Visualization.java

import java.awt.Graphics;
public interface Visualization
{
     /**
      * Draw method will define the cell shape drawing
      * @param g A Graphics class
      */
      public void draw(Graphics g);
}
     

Then we will implement the draw(Graphics) method in subClasses of Cell namely:


[Contents] [Next] [Previous]