Methods of Java · Introduction to Java Programming

Polymorphism with Variables

Watch lectures

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 @Override allowed on fields!).
  • Access via super.name for 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.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules

Polymorphism with Variables — Introduction to Java Programming — PYQDeck