Polymorphism (originating from Greek meaning "many forms") is the ability of an object or method to take on multiple operational behaviors depending on context. In Java, polymorphism is divided into two fundamental types:
javac.protected, child cannot make it private; it can be protected or public).final, static, and private methods cannot be overridden.Dynamic Method Dispatch occurs when a superclass reference variable holds a subclass Heap object:
// Base Abstract Class
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a smooth Circle with radius calculation.");
}
}
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a 4-cornered Rectangle.");
}
}
public class DynamicDispatchDemo {
public static void main(String[] args) {
// UPCASTING: Superclass reference holds subclass object
Shape s1 = new Circle();
Shape s2 = new Rectangle();
// JVM determines which draw() to call at RUNTIME based on Heap object:
s1.draw(); // Output: Drawing a smooth Circle...
s2.draw(); // Output: Drawing a 4-cornered Rectangle.
}
}
Frequent Exam Question: "Can variables be overridden in Java?"
Answer: No! In Java, variables are NEVER polymorphic. If a subclass declares a variable with the same name as a superclass variable, it merely shadows (hides) the parent variable. Field access is resolved at compile time based strictly on the reference type, NOT the runtime Heap object!
Now let us explore Encapsulation, JavaBeans conventions, and data hiding. Proceed to: Java Encapsulation & Getters/Setters →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Compile-time polymorphism counterpart.
Superclass and subclass relationships.
Interface-based polymorphism.
Abstract methods and contracts.