Java Reference
In-Depth Information
14
15
abstract class
Animal {
16
Animal
class
/** Return animal sound */
17
public abstract
String sound();
18 }
19
20
class
Chicken
extends
Animal
implements
Edible {
21 @Override
22
implements Edible
public
String howToEat() {
howToEat()
23
return
"Chicken: Fry it"
;
24 }
25
26 @Override
27
public
String sound() {
28
return
"Chicken: cock-a-doodle-doo"
;
29 }
30 }
31
32
class
Tiger
extends
Animal {
33 @Override
34
Tiger class
public
String sound() {
35
return
"Tiger: RROOAARR"
;
36 }
37 }
38
39
abstract class
Fruit
implements
Edible {
40
implements Edible
// Data fields, constructors, and methods omitted here
41 }
42
43
class
Apple
extends
Fruit {
44 @Override
45
Apple
class
public
String howToEat() {
46
return
"Apple: Make apple cider"
;
47 }
48 }
49
50
class
Orange
extends
Fruit {
51 @Override
52
Orange
class
public
String howToEat() {
53
return
"Orange: Make orange juice"
;
54 }
55 }
Tiger: RROOAARR
Chicken: Fry it
Chicken: cock-a-doodle-doo
Apple: Make apple cider
This example uses several classes and interfaces. Their inheritance relationship is shown
in Figure 13.4.
The
Animal
class defines the
sound
method (line 17). It is an abstract method and will be
implemented by a concrete animal class.
The
Chicken
class implements
Edible
to specify that chickens are edible. When a class
implements an interface, it implements all the methods defined in the interface with the exact
signature and return type. The
Chicken
class implements the
howToEat
method (lines
22-24).
Chicken
also extends
Animal
to implement the
sound
method (lines 27-29).
Search WWH ::
Custom Search