Java
Polymorphism basics
Learn superclass reference with subclass object.
Polymorphism basics
Polymorphism lets a superclass reference hold a subclass instance. In Java every regular method is virtual, so dispatch follows the object's runtime type. Shape s = new Circle(); is valid, and s.area() runs the Circle version. This is called dynamic dispatch.
The same code behaves differently for different types; adding a new subclass does not break callers that use the superclass.
Virtual method dispatch
When you call a method on a superclass reference, Java looks at the runtime type of the object, not the reference type. If you wrote Shape s = new Circle();, then s.area() always calls Circle.area.
The trick is the vtable, a per-type virtual method table. Overridden methods dispatch dynamically; there is no separate virtual keyword in Java.
Exercise Write the Shape and Square classes
Write a simple polymorphism example. Define class Shape with an int area() { return 0; } method. Then define class Square extends Shape with an int side field, a Square(int side) constructor and an overridden area method (return side * side;). In main, create a square with Shape s = new Square(5); and print its area with System.out.println("Area: " + s.area());.
Show example solution
class Shape {
int area() { return 0; }
}
class Square extends Shape {
int side;
Square(int side) { this.side = side; }
int area() { return side * side; }
}
public class Main {
public static void main(String[] args) {
Shape s = new Square(5);
System.out.println("Area: " + s.area());
}
}
Test yourself
-
What does Shape s = new Circle(); show?
- A polymorphic assignment; superclass holds subclass
- Multiple inheritance from two classes
- A generic type parameter
- A static method call
Show answer
A polymorphic assignment; superclass holds subclass — A superclass reference holds a subclass instance; this is the core of polymorphism.
-
Complete the subclass declaration
class Circle ____ Shape {
double area() { return Math.PI * r * r; }
}
Show answer
class Circle extends Shape {
double area() { return Math.PI * r * r; }
}
-
Match the polymorphism concepts
- virtual
- Default method behavior in Java
- override
- Redefining a method in a subclass
- extends
- Declares class inheritance
- super
- Parent class reference
Next lesson: Dynamic binding