Polymorphism

Keywords

  • super keyword: it’s like the this keyword, except it accesses the superclass instead of the current class
  • @Override annotation: specifies that a method overrides a method in the superclass (technically not needed but good for readability)
    • final methods can’t be overridden

Vocab

  • Superclass / Parent Class: Class that has common fields and methods shared by subclasses
  • Subclass / Child Class: Class that extends functionality of the superclass (does not inherit constructors)
  • Polymorphism: The ability to treat objects of different classes through a common interface, allowing for method overriding
  • Static vs dynamic types
    • Static types: The type of the variable you declare at compile time (when you say Animal bozo, Animal is the static type)
    • Dynamic types: The type of the variable at runtime (when you say = new Monkey(), monkey is the dynamic type)

Polymorphism/polymorphic/etc

  • Polymorphic reference variables can refer to objects of different classes in the code
  • Polymorphic methods are overriden in at least one subclass
  • Polymorphism: act of executing overriden non-static method at runtime based on the actual object type
Animal
makeSound()
System.out.println("Some sound...");
Dog
makeSound()
System.out.println("Woof!");
Cat
makeSound()
System.out.println("Meow!");
Click on a class to see polymorphism in action!