Java Reference
In-Depth Information
Listing 17-22 shows using a
Turtle
object as a
Turtle
type,
Walkable
type, and
Swimmable
type.
Listing 17-22.
Using the Turtle Class
// TurtleTest.java
package com.jdojo.interfaces;
public class TurtleTest {
public static void main(String[] args) {
Turtle turti = new Turtle("Turti");
// Using Turtle type as Turtle, Walkable and Swimmable
letItBite(turti);
letItWalk(turti);
letItSwim(turti);
}
public static void letItBite(Turtle t) {
t.bite();
}
public static void letItWalk(Walkable w) {
w.walk();
}
public static void letItSwim(Swimmable s) {
s.swim();;
}
}
Turti (a turtle) is biting.
Turti (a turtle) is walking.
Turti (a turtle) is swimming.
Note that a
Turtle
type variable can access all three methods,
bite()
,
walk()
, and
swim()
like so:
Turtle t = new Turtle("Turti");
t.bite();
t.walk();
t.swim();
When you use a
Turtle
object as the
Walkable
type, you can access only the
walk()
method. When you use
a
Turtle
object as the
Swimmable
type, you can access only the
swim()
method. The following snippet of code
demonstrates this rule:
Turtle t = new Turtle("Trach");
Walkable w = t;
w.walk(); // OK. Using w, you can access only the walk() method of Turtle object
Swimmable s = t;
s.swim(); // OK. Using s you can access only the swim() method