Our first bit of Java code in Lesson A1 will display a square in a window as shown in Figure 2.1. Although this program is very simple, it illustrates the fundamental strategy of an object-oriented program.
Figure 2.1 - DrawSquare
The following is the Java class that we encountered in the previous lesson:
Code Sample 2.1 - DrawSquare.java
The class is called DrawSquare
and the class includes two methods. The first method, DrawSquare(), is named exactly the same as the class and is used in the construction of new instances of this class. The second method is called draw(), and it is where most of the action for this class takes place.
The DrawSquare
constructor calls SketchPad
’s constructor to create a new SketchPad
object named myPaper
with an initial size of 300 by 300 pixels. This will happen every time a new object of DrawSquare
is created.
Another object called myPencil
is created using the DrawingTool
constructor with a drawing area represented by the myPaper
object.
The method named draw() contains only those instructions directly related to the actual drawing of our square.
In order to run this program, we will create what is called a driver or throwaway class. This class serves the purpose of testing DrawSquare. The DrawSquare class should be tested and used in a small class to ensure that it is working as expected. We can then take the DrawSquare class and safely use it in other programs later on.