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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

230 Chapter 16 ■ <strong>Programming</strong> in the large<br />

><br />

As an example, we declare an interface named Displayable. Any class complying<br />

with this interface must include a method named display which displays the object.<br />

The interface declaration in Java is:<br />

public interface Displayable {<br />

void display(Graphics paper);<br />

}<br />

Now we write a new class, named Square, which represents square graphical<br />

objects. We say in the header of the class that it implements Displayable. We include<br />

within the body of the class the method display:<br />

public class Square implements Displayable {<br />

}<br />

private int x, y, size;<br />

public void display(Graphics paper) {<br />

paper.setColor(Color.black);<br />

paper.drawRectangle(x, y, size, size);<br />

}<br />

// other methods of the class Square<br />

As the heading states, this class (and any object created from it) con<strong>for</strong>ms to the<br />

Displayable interface. It means that any object of this class can be passed around a<br />

program and we are confident that, when necessary, it can be displayed by calling its<br />

method display.<br />

SELF-TEST QUESTION<br />

16.5 We wish to write a new class Circle that implements the<br />

Displayable interface. Write the header <strong>for</strong> the class.<br />

16.8 ● Multiple interfaces<br />

Just as a TV has interfaces both to a power source and to a signal source, so can we<br />

specify that a class implements a number of interfaces.<br />

Java, <strong>for</strong> example, is a language that provides single inheritance – a class can inherit<br />

from (or be the subclass of) only one class. The class structure is a tree, with the root at<br />

the top, in which a class can have many subclasses but only one superclass. Figure 16.3<br />

shows illustrative classes Circle and Game as subclasses of superclass JFrame. Each class<br />

appears only within a single tree and each class has only a single superclass.<br />

>

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

Saved successfully!

Ooh no, something went wrong!