









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










In our intuitive description of ob ject-oriented programming presented in Chapter 1, we describ ed an ob ject-oriented program as a universe of interacting agents. However, in our rst example Java program, in Chapter 4, we did not actually create any new ob jects, but only used the static pro cedure named main in the program class. Our second program is slightly more complex in structure, although hardly more com- plicated in functionality. It places a graphical window on the user's screen, draws a ball that b ounces around the window for a few moments, and then halts.
Our second example program, or paradigm, is constructed out of two classes. The rst of these app ears in Figure 5.1. Again, we have added line numb ers for the purp oses of
reference, however these are not part of the actual program.^1 The reader should compare this program to the example program describ ed in the previous chapter, noting b oth the similarities and di erences. Like the previous program, this program imp orts (on line 1) information from the Java library. Like the earlier program, execution will b egin in the pro cedure named main, (lines 3 through 6), which is declared as static, void and public. Like all main programs, this pro cedure must take as argument an array of string values, which are, in this case, b eing ignored. However, this program also incorp orates a numb er of new features. These are summa- rized by the following list, and will b e the sub ject of more detailed discussion in subsequent sections.
The class de nes a numb er of private internal variable elds, some of which are con- stant, some of which are initialized but not constant, and some of which are not initialized. These data elds will b e describ ed in detail in Section 5.1.
The main program creates an instance of the class BallWorld. This ob ject is initialized by means of a constructor. A constructor is a function that automatically ties together the actions of ob ject creation and ob ject initialization. Constructors will b e intro duced in Section 5.2.
The class is declared as an extension of an existing Java class named Frame. This technique is called inheritance, and is the principal means in ob ject-oriented languages for constructing new software abstractions that are variations on existing data typ es. Inheritance will b e intro duced in Section 5.3, and will b e more extensively studied b eginning in Chapter 8.
The output displayed in a window by this program is created using some of the graph- ics primitives provided by the Java run-time library. These graphics op erators are explained in Section 5.4.
We have seen in the previous chapter (Section 4.4) how data elds can b e declared within a class and how they can b e initialized. The example program here includes features we have not seen in our previous programs in the four data elds declared on lines 7 to 10:
public static final int FrameWidth = 600; // 7 public static final int FrameHeight = 400; // 8 private Ball aBall; // 9 (^1) In order to draw more attention to the Java co de itself, the programs presented in this text have purp osely b een written using very few comments. In practice comments would usually b e used to describ e each function in a class.
private int counter = 0; // 10
Recall that the keyword public means that the variables b eing declared can b e accessed (that is, used directly) anywhere in a Java program, while those that are declared as private can b e used only within the b ounds of the class description in which the declaration app ears. Recall also that the keyword static means that there is one instance of the data eld, shared by all instances of the class. The mo di er keyword nal generally means that this is the last time when an ob ject is changed. It is here applied to a variable declaration; we will in later chapters see how the mo di er can also b e applied to a function de nition. When used with a variable declaration, the declaration must also include an initialization, as shown here. Variables that are static and nal are used to create symb olic names for constants, as they are variables that are guaranteed to exist only in one place, and not change values. Because they cannot b e mo di ed, there is less reason to encapsulate a static nal variable by declaring it private. Thus, such values are often made public, as shown here. The particular symb olic values b eing de ned in this program represent the height and width of the window in which the application will eventually pro duce its output. Symb olic constants are useful in programs for a numb er of di erent reasons:
By b eing de ned in only one place, they make it easy to subsequently change, should circumstances require. For example, changing the height and or width of the window merely requires editing the le to change the values b eing used to initialize these symb olic constants, rather than hunting down all lo cations in the co de where the quantities are used.
When subsequently used elsewhere in the program, the symb olic name helps do cument the purp ose of the constant values.
The counter data eld is an integer value, initialized to zero:
private int counter = 0; // 10
Because the eld is declared private we know it can b e used only within the b ounds of the class de nition. Because it was not declared static, we know that each instance of the class will hold its own di erent value. Because it was not declared as nal we know that the value b eing assigned is simply the initial value the variable will hold, but that it subsequently could b e reassigned. We will see how this variable is used when we discuss the graphical asp ects of the current program.
private Ball aBall; // 9
The nal data eld is declared as an instance of class Ball, which is the second class used in the creation of our example program. A ball is an abstraction that represents a b ouncing ball. It is represented by a colored circle that can move around the display surface. The
class Ball will b e describ ed in Section 5.5. How this eld is initialized is describ ed in the next section.
As we noted at the b eginning of the chapter, one of the ma jor topics we address in this chapter is the creation of new ob jects. This o ccurs in two places in the program shown in Figure 5.1. The rst is in the main program, which creates an instance of the class BallWorld.
BallWorld world = new BallWorld (Color.red); // 4
The new op erator is always used to create a new ob ject. In this case, it is b eing used to create an instance of BallWorld, which (we will see in the next section) is the name given to the window in which the program will display its output. The new op erator is followed by a class name, indicating the typ e of ob ject b eing created. A parenthesized list then gives any arguments needed in the initialization of the ob ject. Ob ject creation and ob ject initialization are intimately tied in concept, and it is imp or- tant that a programming language also bring these concepts together. Without supp ort from the programming language, two typ es of errors can easily o ccur:
An ob ject is created, but it is used b efore it is initialized.
An ob ject is created, and initialized multiple times b efore it is used.
The language Java uses a concept called a constructor to guarantee that ob jects are placed into a prop er initial state the moment they are created. A constructor b ears a strong resemblance to a function, however the name of the function matches the name of the class in which it app ears, the function do es not sp ecify a return typ e, and the user will never directly execute the constructor. However, like a function, a constructor can have arguments, and the b o dy of the constructor consists of a sequence of statements. In our example program the constructor o ccurs in lines 11 to 19:
private BallWorld (Color ballColor) f// constructor for new window 11 // resize our frame, initialize title 12 setSize (FrameWidth, FrameHeight); // 13 setTitle ("Ball World"); // 14
// initialize aBall data eld 15 aBall = new Ball (10, 15, 5); // 16 aBall.setColor (ballColor); // 17 aBall.setMotion (3.0, 6.0); // 18 g // 19
that the programmer need only b e concerned with those features of the application that distinguish the program from other window applications. The programming language Java uses the class Frame to represent a generic window. By saying that the class BallWorld extends the class Frame, we indicate that our new class, the ball world, is a typ e of frame, but a more sp ecialized typ e with a single purp ose. The class Frame de nes co de to p erform actions such as resizing the window, arranging for the window to b e displayed on the workstation screen, and so on. By extending the class Frame, our new class inherits this functionality, which means the abilities are made available to the new class, and do not need to b e rewritten anew.
public class BallWorld extends Frame f // 2
By executing the example program the reader can verify that the window exhibits the functionality we exp ect of graphical windows; the ability to move, resize, and iconify, even though the program do es not explicitly de ne any co de to supp ort these b ehaviors. (The reader might also note some exp ected b ehaviors that are not provided. For example, the handling of menu items and the close or quit b ox. In a later chapter we will describ e how these features can b e provided.) We can observe the use of inheritance in the variety of metho ds that are invoked in our example program, but are not de ned by the class BallWorld. These functions are instead inherited from the parent class Frame. Two examples are the functions setSize and setTitle invoked in the BallWorld constructor. These functions set the dimensions (in pixels) and title value for the window, resp ectively.
private BallWorld (Color ballColor) f// constructor for new window 11 // resize our frame, initialize title 12 setSize (FrameWidth, FrameHeight); // 13 setTitle ("Ball World"); // 14 ... g // 19
Another example is the function show, which is invoked in the static pro cedure main after the instance of BallWorld has b een created. The show function arranges for the window to app ear on the display surface, and then for the surface of the window to b e drawn.
public static void main (String [ ] args) f // 3 BallWorld world = new BallWorld (Color.red); // 4 world.show (); // 5 g // 6
Graphics in Java is provided as part of the AWT, or the Abstract Windowing Toolkit. The Java AWT is an example of a software framework. The idea of a framework is to provide the structure of a program, but no application sp eci c details. The overall control, the ow of execution, is provided by the framework, and therefore do es not need to b e rewritten for each new program. Thus, the programmer do es not \see" the ma jority of the program co de. This is illustrated by the actions that o ccur subsequent to the program issuing the show metho d that is inherited from the class Frame. The window in which the action will take place is created, and the image of the window must b e rendered. To do so, the show metho d invokes a function named paint, passing as argument a graphics object. The programmer de nes the app earance of the window by providing an implementation of the function paint. The graphics ob ject passed as argument provides the ability to draw a host of items, such as lines and p olygons as well as text. In our example program we use the paint pro cedure for two purp oses. The only image in the window itself is the b ouncing ball. The image of the ball is pro duced by invoking the paint metho d in the class Ball (see Figure 5.2). The second purp ose of the paint metho d is to provide a simple means of up dating the lo cation for the ball. The ball is moved slightly, checking to see if the resulting new lo cation is outside the b ounds of the window. If so, the direction of the ball is reversed. Finally, invoking the repaint metho d (also inherited from Frame) indicates to the framework that the window should b e redrawn, and the cycle continues.^2 A counter is used to prevent the program from running inde nitely, invoking the function System.exit after a certain numb er of iterations. (Later programs will use other techniques to halt the program).
public void paint (Graphics g) f // 20 // rst, draw the ball 21 aBall.paint (g); // 22 // then move it slightly 23 aBall.move(); // 24 if ((aBall.x() < 0) jj (aBall.x() > FrameWidth)) // 25 aBall.setMotion (-aBall.xMotion(), aBall.yMotion()); // 26 if ((aBall.y() < 0) jj (aBall.y() > FrameHeight)) // 27 aBall.setMotion (aBall.xMotion(), -aBall.yMotion()); // 28 // nally, redraw the frame 29 counter = counter + 1; // 30 if (counter < 2000) repaint(); // 31 else System.exit(0); // 32 (^2) Some readers might ob ject that the control of the animation has little to do with the rendering of the image on the window, and thus do es not b elong in the paint routine. While there is merit to this argument, this is also the simplest way to make simple animations. In later chapters we will present more robust ways to control animations.
public class Ball f // a generic round colored ob ject that moves protected Rectangle location; // p osition on graphic surface protected double dx, dy; // x and y comp onents of motion vector protected Color color; // color of ball
public Ball (int x, int y, int r) f // ball with given center and radius location = new Rectangle(x-r, y-r, 2 r, 2 r); dx = 0; dy = 0; // initially no motion color = Color.blue; g
// functions that set attributes public void setColor (Color newColor) f color = newColor; g
public void setMotion (double ndx, double ndy) f dx = ndx; dy = ndy; g
// functions that access attributes of ball public int radius () f return location.width / 2; g
public int x () f return location.x + radius(); g
public int y () f return location.y + radius(); g
public double xMotion () f return dx; g
public double yMotion () f return dy; g
public Rectangle region () f return location; g
// functions that change attributes of ball public void moveTo (int x, int y) f location.setLocation (x, y); g
public void move () f location.translate ((int) dx, (int) dy); g
public void paint (Graphics g) f g.setColor (color); g.fillOval (location.x, location.y, location.width, location.height); g g
Figure 5.2: Implementation of the class Ball
x and y), can move to a new p osition (used in function moveTo), and can transliterate on the 2-dimensional surface (used in the function move). Finally, the function paint uses two op erations that are provided by the class Graphics in the Java library. These are the ability to set the current color for rendering graphics (setColor) and to display a painted oval at a given lo cation on the window ( llOval).
Every instance of a class maintains its own internal data elds. We can illustrate this by making variations on our sample program. The simplest change is to mo dify the main routine to create two indep endent windows. Each window will have a di erent ball, each window can b e indep endently moved or resized.
public static void main (String [ ] args) f // create rst window with red ball BallWorld world = new BallWorld (Color.red); world.show(); // now create a second window with yellow ball BallWorld world2 = new BallWorld (Color.yellow); world2.show(); g
The reader should try making this change, and observe the result. Note how one window is b ouncing a red ball, and the second is b ouncing a yellow ball. This indicates that each instance of class BallWorld must b e maintaining its own Ball value, as a ball cannot b e b oth red and yellow at the same time. A second variation illustrates even more dramatically the indep endence of di erent ob- jects, even when they derive from the same class. The class MultiBallWorld (Figure 5.3) is similar to our initial program, only it creates a collection of balls, rather than just a single ball. Only the lines that have changed are included, and those that are elided are the same as the earlier program. The new program declares an array of Balls, rather than just a single ball. Note the syntax used to declare an array. As we noted in the previous chapter, arrays in Java are di erent from arrays in most other languages. Even though the array is declared, space is still not set aside for the array elements. Instead, the array itself must b e created (again with a new command):
ballArray = new Ball [ BallArraySize ];
Note how the size of the array is sp eci ed by a symb olic constant, de ned earlier in the program. Even then, however, the array elements cannot b e accessed. Instead, each array element must b e individually created, once more using a new op eration:
for (int i = 0; i < BallArraySize; i++) f ballArray[i] = new Ball(10, 15, 5); ballArray[i].setColor (ballColor); ballArray[i].setMotion (3.0+i, 6.0-i); g
Each ball is created, and initialized with the given color, and set in motion. We have used the lo op index variable to change the direction of motion slightly, so that each ball will initially move in a di erent direction. When executed, ten di erent balls will b e created. Each ball will maintain its own lo cation and direction. As each ball is asked to paint it will display its value on the window. Each ball will then move, indep endently of all other balls.
The two ma jor themes intro duced in this chapter have b een the creation of new ob jects using the op erator new, and the de nition of new classes using inheritance to extend an existing class. Topics discussed in this chapter include the following:
Data elds which are declared nal cannot b e subsequently rede ned. A static and nal value is the technique normally used to create a symb olic constant.
New ob jects are always created using the op erator new.
When a new ob ject is created, the constructor for the class of the ob ject is automat- ically invoked as part of the creation pro cess. The constructor should guarantee the ob ject is prop erly initialized. A constructor is a function that has the same name as the class in which it is de ned.
Any arguments used by the constructor must app ear in the new statement that creates the corresp onding ob ject.
Classes can b e de ned using inheritance. Such classes extend the functionality of an existing class. Any public or protected data elds or functions de ned in the parent class b ecome part of the new class.
The class Frame can b e used to create simple Java windows. This class can b e extended to de ne application-sp eci c windows. The framework provided by the Java AWT displays a frame (a window) when the frame ob ject is given the message show. To create the image shown in the window the message paint is used. The programmer can de ne this metho d to pro duce application- sp eci c pictures.
The paint metho d is given as argument an instance of the library class Graphics. This ob ject can b e used to create a variety of graphical images.
The class Rectangle (used in our class Ball) is a library class that represents a rect- angular region on the two-dimensional window surface. The class provides a large amount of useful functionality.
Multiple instances of the same class each maintain their own separate data elds. This was illustrated by creating multiple indep endent Ball ob jects, which move inde- p endently of each other.
We will use the Ball class in case studies in Chapters 6, 7, 8 and 20. The topic of inheritance is simple to explain, but has many subtle p oints that can easily trap the unwary. We will examine inheritance in detail in Chapters 8 through 11. The AWT will b e examined in more detail in Chapter 13.