๐Ÿงญ Topic: OOP - Inheritance & Polymorphism

Quick Overview :

This topic explores advanced Object-Oriented Programming concepts including inheritance, polymorphism, abstraction through abstract classes and interfaces, method overriding, and casting. These principles enable code reuse, flexibility, and extensibility in Java applications.


๐Ÿ“Œ Covered in This Topic

The Four Pillars of OOP (Review)

  • Encapsulation: Bundling data and methods together while restricting direct access to the internal state
  • Polymorphism: Allowing the same method call to behave differently depending on the object type
  • Inheritance: Creating a new class that reuses and extends the behavior of an existing class
  • Abstraction: Hiding implementation details and exposing only the essential functionality

Inheritance

  • What is Inheritance?

    • A relationship between a more general class (superclass) and a more specialized class (subclass)
    • A subclass inherits data and behavior from a superclass
    • Represents an โ€œis-aโ€ relationship
    • You can always use a subclass object in place of a superclass object (substitution principle)
  • Benefits of Inheritance:

    • Reduce code duplication
    • Improves code organization
    • Makes systems easier to extend
    • Helps model real-world hierarchies
  • Important Terms:

    • Superclass: Base or foundation in an inheritance hierarchy; defines common fields and methods
    • Subclass: Inherits from parent class; gains access to its fields and methods; can extend or customize behavior
    • Inherited fields and methods: Properties and functions defined in parent class that become available to child class
    • Overriding behavior: When a child class replaces a method from the parent class with its own version
  • Javaโ€™s Inheritance Rule:

    • Java supports single inheritance for classes (a class can inherit from only one parent class)
    • Interfaces allow classes to adopt multiple behaviors

The super Keyword

  • Accessing Parent Class Methods: Call a method defined in parent class, even if overridden
  • Calling The Parent Constructor: super() initializes fields defined in parent class; must be first statement in constructor
  • Accessing Parent Class Fields: super.fieldName explicitly refers to parentโ€™s version when naming conflicts exist
  • Avoiding Naming Conflicts: Distinguishes between parent and child behavior when method names or variables overlap

Method Overriding

  • When the same method is defined in both superclass and subclass, the subclass method overrides the superclass method
  • Rules:
    • Same method name, same return type, same parameter list
    • Cannot override final and static methods
    • Must override abstract methods of the superclass
  • When to Use:
    • Base behavior needs to change in a subclass
    • Each subclass has its own implementation
    • Method describes behavior that varies between types

Polymorphism

  • The ability to use one type to represent multiple behaviors

  • One method call โ†’ different execution depending on the actual object

  • A key OOP feature enabling flexibility and extensibility

  • Two Types of Polymorphism:

    • Compile-time: Same method name, different parameters; resolved at compile time (method overloading)
    • Runtime: Child class redefines a method from the parent; resolved at runtime (method overriding)
  • How Runtime Polymorphism Works:

    • Reference is of the parent type
    • Object is of the child type
    • JVM decides which method implementation to run at runtime
    • Common Structure: Parent p = new Child();
    • Method Call: p.someMethod();
    • JVM dynamically binds the correct overridden method
    • Actual behavior depends on real object type, not reference type

Casting

  • Upcasting: Child โ†’ Parent; Safe; Required for polymorphism
  • Downcasting: Parent โ†’ Child; Potentially unsafe; Safe only if object is truly of the child type
  • Use instanceof to check before casting

Abstraction

  • Focuses on showing only essential features while hiding implementation details
  • In Java, abstraction is mainly implemented using:
    1. Abstract classes
    2. Interfaces
  • Helps developers:
    • Manage complexity
    • Build flexible architectures
    • Define clear responsibilities between components

Abstract Classes

  • Represents a general concept that provides shared structure and behavior for its subclasses
  • Cannot be instantiated directly; meant to be extended by other classes
  • Abstract Method: Declared in an abstract class; must be overridden by subclasses

Interfaces

  • Contract / Capability: Defines a contract that classes must follow

  • Represents what an object โ€œcan doโ€ rather than โ€œwhatโ€ it is

  • Multiple Inheritance of Type: Java allows implementing multiple interfaces

  • Loose Coupling: Reduces dependency between classes

  • Interface vs Class:

    • No constructors (cannot be instantiated)
    • Methods were public abstract (before Java 8)
    • All fields inside interfaces are public static final
  • Modern Interface Features:

    • Default Methods: Provide a method implementation inside an interface
    • Static Methods: Define static utility methods in interfaces
    • Functional Interface: Contains exactly one abstract method

๐Ÿ“‘ Slides & Materials


๐Ÿ› ๏ธ Workshop & Assignments

๐Ÿ’ฌ Workshop: Vehicle Management System

  • ๐Ÿ“‚ WS-03-advanced-oop Repository
  • Build a vehicle hierarchy demonstrating OOP principles
  • Class Hierarchy: Vehicle (abstract) โ†’ Car (abstract) โ†’ GasCar / ElectricCar โ†’ SportsCar
  • Interfaces: Serviceable, Refuelable, Chargeable
  • Tasks:
    • Complete Vehicle: getters, addMileage() with validation, abstract getEnergyType()
    • Complete Car: constructor with super, implement abstract methods, needsService(), performService()
    • Complete GasCar: refuel(), getEnergyType(), override showDetails()
    • Complete ElectricCar: charge(), getEnergyType(), override showDetails()
    • Complete SportsCar: override showDetails() with specific features
    • Complete VehicleInspector: inspect(Vehicle v) using instanceof
    • Bonus: Add HybridCar implementing both Refuelable and Chargeable

๐Ÿงฎ Assignment: Java Knight RPG

  • ๐Ÿ“‚ HW-04-JAVA-KNIGHT Repository
  • Turn-based RPG with Roguelike elements - Text-based role-playing game
  • OOP Requirements: Must utilize Inheritance, Interfaces, Abstract Classes, Encapsulation, Polymorphism, Overloading, and Overriding
  • Core Mechanics:
    • Character Classes: Knight, Assassin, Wizard with distinct base stats
    • Resource System: Unified Mana/Stamina for all player actions
    • 5 Standard Actions: Light Attack (0 Mana), Heavy Attack, Defend, Heal, Special Ability
    • Special Abilities: Wizard (damage + heal), Assassin (invisibility + critical), Knight (stun + heavy damage)
    • Enemies: Goblin (high crit), Skeleton (resurrection), Vampire (lifesteal), Dragon (boss)
    • Key Collection: Must collect 3 unique keys (20% drop rate) before fighting Dragon
    • XP & Leveling: Earn XP from enemies, level up increases Max HP and Mana
  • Bonus Features: Merchant system, inventory management, PvP mode, party system
  • Deadline: May 11th (21 Ordibehesht)

RepositoryDescription
๐Ÿ“‚ WS-03-advanced-oopWorkshop: Vehicle Management System - Complete TODO sections implementing inheritance, interfaces, and polymorphism
๐Ÿ“‚ HW-04-JAVA-KNIGHTAssignment: Java Knight RPG - Build a complete turn-based RPG applying all OOP principles

๐ŸŒ Additional Resources


โฉ Navigation


Tip :

The key to mastering inheritance and polymorphism is understanding the โ€œis-aโ€ relationship. When designing class hierarchies, always ask: โ€œIs a SportsCar a Car? Is a Car a Vehicle?โ€ If yes, inheritance is appropriate. For capabilities like โ€œcan be servicedโ€ or โ€œcan be refueled,โ€ use interfaces. This distinction will make your code more flexible and maintainable. Also, remember that good OOP design is about avoiding code duplication while creating clear, logical relationships between classes!