21.08.2013 Views

Software Engineering for Students A Programming Approach

Software Engineering for Students A Programming Approach

Software Engineering for Students A Programming Approach

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

210 Chapter 15 ■ Object-oriented programming<br />

><br />

><br />

Bomb to create two objects, storing them in an array list named game, and displaying<br />

them. The display is shown in Figure 15.1.<br />

Alien alien = new Alien(20, 20, 100);<br />

Bomb bomb = new Bomb(80, 80, 10);<br />

ArrayList game = new ArrayList();<br />

game.add(alien);<br />

game.add(bomb);<br />

<strong>for</strong> (int s = 0; s < game.size(); s++) {<br />

Object item = game.get(s);<br />

Sprite sprite = (Sprite) item;<br />

sprite.display(paper);<br />

}<br />

Polymorphism is in use here – the method display is called on two occasions with<br />

different results according to which object is in use. You can see that the two calls of<br />

display within the <strong>for</strong> loop:<br />

sprite.display(paper);<br />

give two different outputs. Two different outputs are displayed because the Java system<br />

automatically selects the version of display associated with the class of the object.<br />

When method display is first called, the variable sprite contains the object alien<br />

and so the version of display in the class Alien is called. Then the corresponding<br />

thing happens with bomb. This is the essence of polymorphism.<br />

The class of an object is determined when the object is created using new classes,<br />

and stays the same whatever happens to the object. Whatever you do to an object in a<br />

program, it always retains the features it had when it was created. An object can be<br />

assigned to a variable of another class and passed around the program as a parameter,<br />

but it never loses its true identity.<br />

Polymorphism allows us to write a single concise statement, such as:<br />

sprite.display(paper);<br />

instead of a series of if statements like this:<br />

if (sprite instanceof Alien) {<br />

Alien alien = (Alien) sprite;<br />

alien.display(paper);<br />

}<br />

if (sprite instanceof Bomb) {<br />

Bomb bomb = (Bomb) sprite;<br />

bomb.display(paper);<br />

}<br />

><br />

>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!