Chapter 9: Interfaces and Polymorphism
Sample Interface
public interface Animal
{
String getSound();
}
Sample Interface Implementation
public class Dog implements Animal
{
public String getSound()
{
// whatever
}
// other parts of Dog class
}
public class Cat implements Animal
{
public String getSound()
{
// whatever
}
// other parts of Cat class
}
Definitions
- Polymorphism: the behavior of an object depends on
the actual type of object.
- When behavior is determined at run time, this illustrates
late binding.
- When behavior is determined at compile time, this
illustrates early binding.
Converting Between Classes and Interfaces
Cat myCat = new Cat (...);
Dog myDog = new Dog (...);
Animal myPet;
myCat.getSound(); // early binding
myPet = myCat; // conversion
myPet.getSound(); // polymorphism, late binding
myPet = myDog; // conversion
myPet.getSound(); // polymorphism, late binding
myDog = (Dog) myPet; // conversion
myCat = (Cat) myPet; // error, myPet is not currently a Cat
Lecture Code