Message Dispatch

  • Process of determining which version of a method to execute
  • Java: method signature
    (name and argument types)
  • Python: method name only
  • Based on the original object,
    not data type
Python
class Canine:
    def bark(self) -> None:
        print("I'm scary")


class Dog(Canine): def bark(self) -> None: print("I'm friendly")


class GuideDog(Dog): def bark(self) -> None: print("I'm helpful")


Java
public class Canine {
    public void bark() {
        System.out.println("I'm scary");
    }
}
public class Dog extends Canine { public void bark() { System.out.println("I'm friendly"); } }
public class GuideDog extends Dog { public void bark() { System.out.println("I'm helpful"); } }

Message Dispatch

Depends on object, not data type

Python
dogs: List[Canine] = list()
dogs.append(Canine())
dogs.append(Dog())
dogs.append(GuideDog())
for dog in dogs:
    dog.bark()
# I'm scary # I'm friendly # I'm helpful
Java
Canine[] dogs = new Canine[3];
dogs[0] = new Canine();
dogs[1] = new Dog();
dogs[2] = new GuideDog();
for(Canine dog : dogs){
    dog.bark();
}
// I'm scary
// I'm friendly
// I'm helpful

Checking Type

Python
if isinstance(dog, GuideDog):
    # treat dog like a GuideDog
Java
if (dog instanceof GuideDog) {
    // cast dog to GuideDog type
    GuideDog gDog = (GuideDog) dog 
    // treat gDog as a GuideDog

Best Practices

  • Use inheritance for state and behavior with "real" superclass
  • Use abstract for state and behavior with "imaginary" superclass
  • Use interface for behaviors only