Method Overriding and Polymorphism - 11

Method Overriding

Key Concepts

  • Method Overriding: Hiding of methods by subclasses.
  • Inheritance: Extending class functionality and reusing code.
  • Abstraction: Code written for a superclass works for its subclasses.
  • Polymorphism: Achieved through method overriding, allowing a single method to work differently based on the subclass.
  • Dynamic Dispatch: Java determines which method to call at runtime, irrespective of the variable type.

SuperGoose Example

  • Goose subclasses Animal.
  • The talk method in Goose hides the talk method in Animal.
  • super.talk(): Calls the Animal version of talk from within Goose.

Animal Override Example

  • Demonstrates dynamic dispatch: the instance's version of the method is always called.

Polymorphism

  • Supports writing code that works with any subclass of a superclass.
  • The interface remains consistent, but the implementation varies.

Expression Class

  • Illustrates polymorphism using a simple arithmetic expression class.
  • Includes integer literals, addition, and multiplication.
  • Subclasses: Value, Add, Multiply.
  • Employs inheritance, recursion, and method overriding.

Value Class

  • Represents an integer literal value.

Add Class

  • Represents the addition operator.
  • Uses Expression to store any subclass.
  • .describe() and .evaluate() methods are polymorphic and recursive.

Multiply Class

  • Similar to the Add class, but represents multiplication.

\@Override Annotation

  • Used to prevent errors in method overriding.
  • Ensures the method signature (name and parameter list) is exactly the same as the superclass method.
  • Provides the compiler with extra information to verify overriding.

Software Development Lifecycle (SDLC)

  • An idealized, iterative view of software development.
  • Design: Breaking problems into classes.
  • Implementation: Writing those classes.
  • Classes facilitate testing and maintenance through data hiding and abstraction.