๐งญ 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.fieldNameexplicitly 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
finalandstaticmethods - 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
instanceofto check before casting
Abstraction
- Focuses on showing only essential features while hiding implementation details
- In Java, abstraction is mainly implemented using:
- Abstract classes
- 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
- ๐จโ๐ซ Professor Slides (PDF)
- ๐งโ๐ซ TA Workshop Slides (PDF)
- ๐ฅ Assignment Explanation Videos
๐ ๏ธ 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, abstractgetEnergyType() - Complete
Car: constructor withsuper, implement abstract methods,needsService(),performService() - Complete
GasCar:refuel(),getEnergyType(), overrideshowDetails() - Complete
ElectricCar:charge(),getEnergyType(), overrideshowDetails() - Complete
SportsCar: overrideshowDetails()with specific features - Complete
VehicleInspector:inspect(Vehicle v)usinginstanceof - Bonus: Add
HybridCarimplementing bothRefuelableandChargeable
- Complete
๐งฎ 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,Wizardwith 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
- Character Classes:
- Bonus Features: Merchant system, inventory management, PvP mode, party system
- Deadline: May 11th (21 Ordibehesht)
๐ Repository Links
| Repository | Description |
|---|---|
| ๐ WS-03-advanced-oop | Workshop: Vehicle Management System - Complete TODO sections implementing inheritance, interfaces, and polymorphism |
| ๐ HW-04-JAVA-KNIGHT | Assignment: Java Knight RPG - Build a complete turn-based RPG applying all OOP principles |
๐ Additional Resources
- Oracle Java Tutorials - Inheritance
- Oracle Java Tutorials - Interfaces
- Oracle Java Tutorials - Polymorphism
- Java Abstract Classes vs Interfaces
โฉ Navigation
- โฌ ๏ธ Previous Topic: OOP - Encapsulation
- โก๏ธ Next Topic: OOP Review
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!