| Definition | A mechanism where a class (subclass) inherits fields and methods from another class (superclass). | A mechanism allowing objects of different classes to be treated as instances of a common superclass or interface. |
| Purpose | Enables code reuse and establishes an “is-a” relationship between classes. | Enables flexibility by allowing a single interface to represent different types or behaviors. |
| Mechanism | Achieved using the extends keyword for classes or implements for interfaces. | Achieved through method overriding (runtime) or method overloading (compile-time). |
| Relationship | Creates a hierarchical relationship (e.g., Dog is an Animal). | Allows objects to be processed uniformly despite different implementations (e.g., Animal reference for Dog or Cat). |
| Type | Structural concept (defines class relationships). | Behavioral concept (defines how objects behave or are accessed). |
| Code Example | java<br>class Animal {<br> void eat() { System.out.println("Eating"); }<br>}<br>class Dog extends Animal {}<br> | java<br>class Animal {<br> void sound() { System.out.println("Sound"); }<br>}<br>class Dog extends Animal {<br> @Override<br> void sound() { System.out.println("Woof"); }<br>}<br>Animal a = new Dog();<br>a.sound(); // Outputs: Woof<br> |
| Execution Time | Determined at compile time (class structure is fixed). | Runtime (method overriding) or compile-time (method overloading). |
| Flexibility | Fixed hierarchy; adding new classes requires modifying the structure. | Highly flexible; new subclasses can be added without changing existing code. |
| Dependency | Does not require polymorphism (can exist without overriding). | Often relies on inheritance (for method overriding) or interfaces. |
| Scope | Focuses on sharing and extending code (fields, methods). | Focuses on dynamic behavior or method selection. |