Core Java
12 — Inheritance & Polymorphism
Previous: 11 Constructors & Encapsulation · Next: 13 Abstraction & Interfaces
▶️ java pkg1core/core11Inheritance.java · java pkg1core/core12Polymorphism.java
Inheritance · is-a relationship
1class Animal {2 void speak() { System.out.println("..."); }3}4 5class Dog extends Animal {6 @Override7 void speak() { System.out.println("Woof!"); }8}extendsfor classes (single inheritance only)- Child inherits fields and methods
@Overriderecommended · compiler catches typos
`super` keyword
1class Dog extends Animal {2 Dog(String name) {3 super(); // call parent constructor (must be first)4 }5 @Override6 void speak() {7 super.speak(); // call parent version8 System.out.println("Dog done");9 }10}Polymorphism · one interface, many forms
1Animal a = new Dog(); // upcasting · always safe2a.speak(); // prints "Woof!" · runtime dispatch▶️ Dynamic dispatch: JVM calls the actual object's method, not the reference type.
Overloading vs overriding
| Overloading | Overriding | |
|---|---|---|
| When resolved | Compile time | Runtime |
| Signature | Same name, different params | Same name + params |
| Where | Same class | Subclass |
When NOT to inherit
▶️ Don't inherit just to reuse code · use composition (has-a).
Bad: class Stack extends ArrayList
Good: class Stack { private Deque<T> data; }
Related → 03-interview/02-OopAndSolid.md
Related → 01 Core Java
Next → 13 Abstraction & Interfaces
Source named in this chapter
- core11Inheritancepkg1core/core11Inheritance.java
- core12Polymorphismpkg1core/core12Polymorphism.java