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

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

Valid XHTML 1.0!