Introduction: 9.6.0

  • Polymorphism means “many forms”
    • In Java it means that the method that gets called at runtime depends on the type of object at runtime
      • Each subclass of a parent overrides a parent method, so the behavior of the same method depends on the type
        • inheritance-based polymorphism
  • Variables in java have a compile-time type and a runtime type
    • The compile-time type is the type declared, and the runtime type is the type used in declaration
    • Animal myPet = new Dog();
      • Animal is the compile-time type
      • Dog is the runtime type
  • At compile-time, Java will check if the declared type has or inherits all methods and fields called on it
    • If it isn’t found, we give a compiler error
    • At runtime, the execution environment will look for the same method first in the runtime type, rather than the declared type
      • If it isn’t found, we go up the chain of parent classes until we find it.
    • Java also checks if the object actually being set is the type of the declared variable

Object mypet = new Dog();

mypet.bark();  // Compile error!  java.lang.Object has no method bark()!

Summary: 9.6.2

  • At compile time, methods in the declared type determine the correctness of a non-static method call
  • At run-time, the method in the actual object type is executed for a non-static method call
    • This is called polymorphism!