19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

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

584 Chapter 15 Abstract Classes and Interfaces<br />

public static void eat(Edible stuff) {<br />

stuff.howToEat();<br />

}<br />

Edible interface<br />

Chicken class<br />

Duck class<br />

Broccoli class<br />

interface Edible {<br />

public String howToEat() ;<br />

}<br />

class Chicken implements Edible {<br />

@Override<br />

public String howToEat() {<br />

return "Fry it";<br />

}<br />

}<br />

class Duck implements Edible {<br />

@Override<br />

public String howToEat() {<br />

return "Roast it";<br />

}<br />

}<br />

class Broccoli implements Edible {<br />

@Override<br />

public String howToEat() {<br />

return "Stir-fry it";<br />

}<br />

}<br />

To define a class that represents edible objects, simply let the class implement the Edible<br />

interface. The class is now a subtype of the Edible type, and any Edible object can be<br />

passed <strong>to</strong> invoke the eat method.<br />

✓Point✓ Check<br />

15.27 Give an example <strong>to</strong> show why interfaces are preferred over abstract classes.<br />

15.28 Define the terms abstract classes and interfaces. What are the similarities and differences<br />

between abstract classes and interfaces?<br />

15.28 True or false?<br />

a. An interface is <strong>com</strong>piled in<strong>to</strong> a separate bytecode file.<br />

b. An interface can have static methods.<br />

c. An interface can extend one or more interfaces.<br />

d. An interface can extend an abstract class.<br />

e. An abstract class can extend an interface.<br />

Key<br />

Point<br />

15.9 Case Study: The Rational Class<br />

This section shows how <strong>to</strong> design the Rational class for representing and processing<br />

rational numbers.<br />

A rational number has a numera<strong>to</strong>r and a denomina<strong>to</strong>r in the form a/b, where a is the numera<strong>to</strong>r<br />

and b the denomina<strong>to</strong>r. For example, 1/3, 3/4, and 10/4 are rational numbers.<br />

A rational number cannot have a denomina<strong>to</strong>r of 0, but a numera<strong>to</strong>r of 0 is fine. Every integer<br />

i is equivalent <strong>to</strong> a rational number i/1. Rational numbers are used in exact <strong>com</strong>putations<br />

involving fractions—for example, 1/3 = 0.33333. . . . This number cannot be precisely<br />

represented in floating-point format using either the data type double or float. To obtain<br />

the exact result, we must use rational numbers.

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

Saved successfully!

Ooh no, something went wrong!