Dynamic Method Binding
Given the superclass and 3 subclasses shown in Lesson 32,
the
following class demonstrates dynamic method binding.
public class animalReference
{
public static void main(String[] args)
{
Animal ref; // ref is a
reference variable for class Animal
Dog adog = new Dog("Waldo");
Cat acat = new Cat("Buster");
Cow acow = new Cow("Marple");
ref=adog;
ref.speak();
ref=acat;
ref.speak();
ref=acow;
ref.speak();
}
}
Each reference chooses the correct "speak()"
method based
on the type of Animal selected. The program's ability to select
the correct method needed is known as dynamic method binding.