Polymorphism with Variables
1. What It Means (beginner — variables lie a little!)
Polymorphism = one name, many forms. For variables (fields): child hides parent field (same name!) — which one you get depends on REFERENCE type (NOT object!). Unlike methods (object wins!).
2. Proof Code (exam trace — reference wins!)
class Animal { String name = "Animal"; }
class Dog extends Animal { String name = "Dog"; } // HIDES (not overrides!)
Animal a = new Dog(); // parent ref, child object!
System.out.println(a.name); // Animal! (reference type wins for FIELDS!)
Dog d = new Dog();
System.out.println(d.name); // Dog (own ref!)
// methods differ: a.eat() would run DOG version (object wins for methods!)
3. Field vs Method Rule (exam table — memorize!)
| Member | Decided by | Example (Animal a = new Dog()) |
|---|---|---|
| Field | reference (Animal) |
a.name → Animal |
| Static method | reference | a.show() → Animal version |
| Instance method | object (Dog) |
a.eat() → Dog version (dynamic!) |
4. Traps
- Fields are hidden, NOT overridden (no
@Overrideallowed on fields!). - Access via
super.namefor parent's copy (both copies exist in child object!). - Beginners expect
a.name→ Dog (wrong! fields don't dispatch!).
5. Exam Points
- Field-hiding trace (
a.name→ ?) — 5 marks, very frequent. - Field vs method dispatch table — 5 marks, favourite contrast.