您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)

 

Content Index

Content Page # 21

The "BallWorld" class - version 5

We shall now demonstrate a strength of object orientation -- the ease in which a program designed to work with one object can be made to work with multiple objects. For version 5 of our bouncing ball application we shall add a second, smaller, green bouncing ball.

First, we need to declare another variable to refer to our new Ball object:

private Ball anotherBall;

Then we need to ensure that a new instance of the class Ball is created, and that out "anotherBall" variable is made to refer to this new object. Let's make our new Ball object smaller (radius 25) and start at a different position on screen (200, 200). We shall also make our new Ball object start moving left and upwards (-3, -2) in small steps. We create the new instance, and make "anotherBall" refer to this new instance in the "BallWorld" constructor method:

anotherBall = new Ball(200, 200, 25, -3, -2);

anotherBall.setColor( Color.green );

As you can see, by also sending our "anotherBall" object a "setColor" message, we can make it a green.

We now need to ensure that our second Ball object is displayed, moved and bounces when necessary. This is done with changes in the "paint" method:

anotherBall.paint(g);

anotherBall.move();

// pause as before

...

// make "myBall" bounce as before

...

// make "anotherBall" bounce

if ( anotherBall.getX() < 0 )

anotherBall.setMotion( -anotherBall.getXMotion(), anotherBall.getYMotion() );

if ( anotherBall.getX() > frameWidth )

anotherBall.setMotion(-anotherBall.getXMotion(), anotherBall.getYMotion());

if ( anotherBall.getY() < 0 ) 

anotherBall.setMotion(anotherBall.getXMotion(), -anotherBall.getYMotion());

if ( anotherBall.getY() > frameHeight )

anotherBall.setMotion(anotherBall.getXMotion(), -anotherBall.getYMotion());

The full source file for "BallWorld.java - version 5" is available for viewing (and can be opened in the Kawa editor).

When running version 5 of our BallWorld application should look as follows:

Perform activity 6 – Compilation and running of "BallWorld.java" - version 5

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg