Java Reference
In-Depth Information
public static void
eat(Edible stuff) {
stuff.howToEat();
}
interface
Edible {
public
String howToEat();
Edible
interface
}
class
Chicken
implements
Edible {
@Override
public
String howToEat() {
return
"Fry it"
;
Chicken
class
}
}
class
Duck
implements
Edible {
@Override
public
String howToEat() {
return
"Roast it"
;
Duck
class
}
}
class
Broccoli
implements
Edible {
@Override
public
String howToEat() {
return
"Stir-fry it"
;
Broccoli
class
}
}
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
howToEat
method.
13.27
✓
✓
Give an example to show why interfaces are preferred over abstract classes.
Check
13.28
Point
Define the terms abstract classes and interfaces. What are the similarities and differ-
ences between abstract classes and interfaces?
13.29
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.
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 numera-
tor 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