Understanding Polymorphism
1. Understanding Compile-Time Polymorphism
| Mechanism | Resolution |
|---|---|
| Method overloading | Compiler chooses based on static argument types |
Operator + | String concat or numeric add |
| Generics | Type-checked at compile time |
2. Understanding Runtime Polymorphism
Example: Dynamic dispatch
Animal a = new Dog("Rex");
a.speak(); // "Woof" — Dog.speak() chosen at runtime
| Mechanism | Detail |
|---|---|
| Method override | JVM dispatches based on runtime object type |
| Virtual table (vtable) | Internal lookup mechanism |
3. Using Upcasting
| Aspect | Detail |
|---|---|
| Direction | Subclass → Superclass |
| Implicit | Yes |
| Example | Animal a = new Dog(); |
4. Using Downcasting
| Aspect | Detail |
|---|---|
| Direction | Superclass → Subclass |
| Explicit | Required: Dog d = (Dog) a; |
| Risk | ClassCastException if not actual subtype |
| Safer | Use instanceof check first |
5. Understanding Dynamic Method Dispatch
| Phase | What's used |
|---|---|
| Compile | Reference type (for legality check) |
| Runtime | Actual object type (for method resolution) |
6. Working with Virtual Methods
| Method type | Dispatch |
|---|---|
| Instance (default) | Virtual (overridable) |
static | Non-virtual (class-bound) |
final | Non-virtual (locked) |
private | Non-virtual (not inherited) |
7. Understanding Type Erasure in Generics
| Aspect | Detail |
|---|---|
| Compile time | Generic type parameters checked |
| Runtime | Erased to Object (or upper bound) |
| Consequence | Cannot do x instanceof List<String> |
8. Using Polymorphic Collections
Example: Polymorphic list
List<Animal> zoo = List.of(new Dog("Rex"), new Cat("Mia"));
zoo.forEach(Animal::speak); // dispatches to subclass
| Pattern | Benefit |
|---|---|
| Heterogeneous collection | Single interface to many implementations |
| Extensibility | Add new subtypes without changing client code |
9. Understanding Late Binding
| Term | Meaning |
|---|---|
| Late (dynamic) binding | Method bound at runtime |
| Early (static) binding | Method bound at compile time |
| Java default | Late for instance methods, early for static/final/private |