Java Reference
In-Depth Information
An object of the
Person
class will have a name that will be set in its constructor. When it receives a “walk”
message, that is, when its
walk()
method is called, it prints a message in the standard output.
Let's create a utility class named
Walkables
, which is used to send a specific message to a collection of objects.
Let's assume that you want to add a
letThemWalk() static
method to the
Walkables
class, which accepts an array
of
Person
objects. It sends a “walk” message to all the elements in the array. You can define your
Walkables
class as
follows. The method does what its name suggests; that is, it lets everyone walk!
public class Walkables {
public static void letThemWalk(Person[] list){
for(Person person : list) {
person.walk();
}
}
}
The following snippet of code can be used to test the
Person
and
Walkables
classes:
public class WalkablesTest {
public static void main(String[] args) {
Person[] persons = new Person[3];
persons[0] = new Person("Jack");
persons[1] = new Person("Jeff");
persons[2] = new Person("John");
// Let everyone walk
Walkables.letThemWalk(persons);
}
}
Jack (a person) is walking.
Jeff (a person) is walking.
John (a person) is walking.
So far, you don't see any problem with the design of the
Person
and
Walkables
classes, right? They perform the
actions they were designed to perform. The design of the
Person
class guarantees that its objects will respond to a
“walk” message. By declaring the
Person
array as the parameter type for the
letThemWalk()
method in the
Walkables
class, the compiler makes sure that the call to
persons[i].walk()
is valid, because a
Person
object is guaranteed to
respond to the “walk” message.
Let's expand this project by adding a new class called
Duck
, which represents a duck in the real world. We all
know that a duck can also walk. A duck can do many other things that a person can or cannot do. However, for the
purpose of our discussion, we'll focus on only the walking ability of ducks. You can define your
Duck
class as follows:
public class Duck {
private String name;
public Duck(String name) {
this.name = name;
}
public void walk() {
System.out.println(name + " (a duck) is walking.");
}
}