Java Reference
In-Depth Information
public static void eat(Edible stuff) {
stuff.howToEat();
}
interface Edible {
Edible interface
public String howToEat()
;
}
class Chicken implements Edible {
@Override
Chicken class
public String howToEat()
{
return "Fry it" ;
}
}
class Duck implements Edible {
@Override
Duck class
public String howToEat()
{
return "Roast it" ;
}
}
Broccoli class
class Broccoli implements Edible {
@Override
public String howToEat()
{
return "Stir-fry it" ;
}
}
To define a class that represents edible objects, simply let the class implement the Edible
interface. The class is now a subtype of the Edible type, and any Edible object can be
passed to invoke the eat method.
15.27
Give an example to show why interfaces are preferred over abstract classes.
Check
15.28
Point
Define the terms abstract classes and interfaces. What are the similarities and differ-
ences between abstract classes and interfaces?
15.28
True or false?
a. An interface is compiled into a separate bytecode file.
b. An interface can have static methods.
c. An interface can extend one or more interfaces.
d. An interface can extend an abstract class.
e. An abstract class can extend an interface.
15.9 Case Study: The Rational Class
This section shows how to design the Rational class for representing and processing
rational numbers.
Key
Point
A rational number has a numerator and a denominator in the form a/b , where a is the numer-
ator and b the denominator. For example, 1/3 , 3/4 , and 10/4 are rational numbers.
A rational number cannot have a denominator of 0 , but a numerator of 0 is fine. Every inte-
ger i is equivalent to a rational number i/1 . Rational numbers are used in exact computations
involving fractions—for example, 1/3 = 0.33333 . . . . This number cannot be precisely
represented in floating-point format using either the data type double or float . To obtain
the exact result, we must use rational numbers.
 
 
Search WWH ::




Custom Search