Not all dogs sound alike, however, so to add a little barking variety to the Dog implementation, we should define an alternative bark() method that accepts a barking sound as a string:
class Dog {
void bark() {
System.out.println("Woof.");
}
void bark(String barkSound) {
System.out.println(barkSound);
}
}
This version of Dog is legal because even though we have two bark() methods, the differing signatures allows the Java(TM) interpreter to chose the appropriate method invocation. The method definition syntax "void bark(String barkSound)" indicates that this variation of bark() accepts an argument of type String, referred to within the method as barkSound.
As another example of method overloading, consider the program DogChorus,
which creates two dogs and elicits a different barking behavior for each dog:
public class DogChorus {
public static void main(String[] args) {
Dog fido = new Dog();
Dog spot = new Dog();
fido.bark();
spot.bark("Arf. Arf.");
fido.bark("Arf. Arf.");
System.exit(0);
}
}
Because Dog supports two different barking behaviors, both defined by methods named bark(), we can design our program to associate either barking behavior with, say, fido. In DogChorus, we invoke different barking behaviors for fido and spot. Note that fido changes his bark after hearing spot.
copyright 1996-2000 Magelang Institute dba jGuru