Java Reference
In-Depth Information
What can you do with the reference variable of an interface type? You can access any members of the interface
using its reference type variable. Since your Walkable interface has only one member, which is the walk() method,
you can write code as shown:
// Let the person walk
w1.walk();
// Let the duck walk
w2.walk();
When you invoke the walk() method on w1 , it invokes the walk() method of the Person object because w1 is
referring to a Person object. When you invoke the walk() method on w2 , it invokes the walk() method of the Duck
object because w2 is referring to a Duck object. When you call a method using a reference variable of an interface type,
it calls the method on the object to which it is referring. With this knowledge about an interface, let's revise the code
for your Walkables class. Listing 17-4 contains the revised code. Note that in the revised code for the letThemWalk()
method, all you had to do is to change the parameter type from Person to Walkable . Everything else remains the same.
Listing 17-4. The Revised Walkables Class
// Walkables.java
package com.jdojo.interfaces;
public class Walkables {
public static void letThemWalk(Walkable[] list) {
for (Walkable w : list) {
w.walk();
}
}
}
Listing 17-5 shows how to test your revised classes with the Walkable interface. It creates an array of the Walkable
type. Declaring an array of an interface type is allowed because an array provides a shortcut to create many variables
of the same type. This time, you can pass objects of the Person class as well as the Duck class in one array of the
Walkable type to the letThemWalk() method of the Walkables class, which lets everyone walk together, as shown in
the output.
Listing 17-5. A Test Class to Test the Revised Person, Duck, and Walkables Classes
// WalkablesTest.java
package com.jdojo.interfaces;
public class WalkablesTest {
public static void main(String[] args) {
Walkable[] w = new Walkable[3];
w[0] = new Person("Jack");
w[1] = new Duck("Jeff");
w[2] = new Person("John");
// Let everyone walk
Walkables.letThemWalk(w);
}
}
 
Search WWH ::




Custom Search