Skip to main content
ICT
Lesson A2 - Object Oriented Programming
 
Main   Previous Next
 

A. Our First Java Application page 3 of 10

  1. 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.


  2. Figure 2.1 - DrawSquare

  3. The following is the Java class that we encountered in the previous lesson:


  4. Code Sample 2.1 - DrawSquare.java

  5. 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.

  6. 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.

  7. Another object called myPencil is created using the DrawingTool constructor with a drawing area represented by the myPaper object.

  8. The method named draw() contains only those instructions directly related to the actual drawing of our square.

  9. 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.

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.