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.

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

><br />

><br />

exploit the common features of the classes. We do this by writing a class Sprite that<br />

embodies the commonality. This name is chosen because, in computer games programs,<br />

a sprite is the term <strong>for</strong> a graphical object. Here it is:<br />

class Sprite {<br />

}<br />

protected int x, y;<br />

protected size;<br />

public void moveLeft(int amount) {<br />

x = x - amount;<br />

}<br />

public void moveRight(int amount) {<br />

x = x + amount;<br />

}<br />

You can see that the variables and methods within this class are relevant to all the<br />

game objects. You will also notice that the variables declared at the head of the class<br />

that were described as public, are now described as protected. This means that they<br />

are accessible from any subclasses, as we shall see in a moment.<br />

We can now write class Alien so as to exploit the class Sprite as follows:<br />

class Alien extends Sprite {<br />

}<br />

private ImageIcon alienImage;<br />

public Alien(int newX, int newY, int newSize) {<br />

x = newX;<br />

y = newY;<br />

size = newSize;<br />

alienImage = new ImageIcon("c:/alien.jpg");<br />

}<br />

public void display(JPanel panel) {<br />

Graphics paper = panel.getGraphics();<br />

alienImage.paintIcon(panel, paper, x, y);<br />

}<br />

and you can see that this is now shorter than it was. The operative word in this code is<br />

extends. This is the Java keyword stating that class Alien inherits the features of class<br />

Sprite. All the public variables and methods become part of class Alien. The terminology<br />

is that Alien is a subclass of Sprite, Sprite is the superclass of Alien,<br />

Alien extends Sprite, Sprite is the base class of Alien.<br />

><br />

>

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

Saved successfully!

Ooh no, something went wrong!