Understanding Class Hierarchies and Polymorphism

Aug 17, 2024

Lecture Notes on Class Hierarchies and Polymorphism

Class Hierarchies

  • Subclassing: A subclass can extend a parent class.
    • Example: Employee class and Manager class (extends Employee).
  • Inheritance of Variables and Methods:
    • Subclass inherits instance variables and methods from parent class.
    • Instance variables: name, salary.
    • Methods: setName, setSalary, getName, getSalary, doubleBonus.
  • Access to Private Members:
    • Private variables in the parent class are not visible to the subclass.
    • Access through public methods or by using super to call the parent constructor.

Method Overriding

  • A subclass can override methods from the parent class.
    • Example: Different bonus calculation for Manager vs. Employee.
    • Overridden method maintains the same signature.
  • Using super: To call the overridden method of the parent class if private variables are not accessible.

Static vs. Dynamic Type Checking

  • Static Type: The type declared in the code (e.g., Employee e).
  • Dynamic Type: The actual object type at runtime (e.g., if e is a Manager).
  • Dynamic Dispatch: Java uses dynamic dispatch (runtime polymorphism) to determine which method to invoke based on the object's actual type.
    • Example: Calling bonus on e will invoke the Manager's bonus calculation if e is a Manager.

Polymorphism

  • Runtime Polymorphism: Determined at runtime based on the actual object type.
  • Overloading: Same method name with different signatures, determined at compile-time (static).
    • Example: sort method in Java's arrays class for different types (int, double).
  • Two Key Differences:
    • Overloading: Static decision based on argument types.
    • Dynamic dispatch: Runtime decision based on the actual object type.

Type Casting and Reflection

  • Type Casting: Convert a variable of one type into another (e.g., Employee e can be cast to Manager).
    • Syntax: (Manager)e.
    • Must ensure the cast is valid to avoid runtime errors.
  • Instanceof Operator: Check if an object is an instance of a specific class to avoid illegal casts.
  • Reflection: Allows querying the status of an object at runtime (e.g., determining its type).

Structural Polymorphism

  • Concept: Functions can operate on different types as long as they share a common capability (e.g., comparability).
  • Generics in Java: Allows for flexible function definitions based on properties of types.

Summary

  • Subclasses can add variables and methods, and override existing methods from parent classes.
  • Dynamic dispatch allows for runtime decision-making in method calls, enabling polymorphic behavior.
  • Type casting and reflection provide additional flexibility in working with types, while structural polymorphism facilitates the reuse of functions across different types.