Polymorphism basics
- Java course
- Intermediate
- Lesson 59/116
- 5 min
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.
Practice 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());.
Starter code
// Define the Shape class: area returns 0
// Square extends Shape; area is overridden
// Assign a Square instance as Shape and print its areaSample 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());
}
}Expected output
Area: 25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Shape s = new Circle(); show?
- A polymorphic assignment; superclass holds subclass Correct answer
- Multiple inheritance from two classes
- A generic type parameter
- A static method call
Explanation: A superclass reference holds a subclass instance; this is the core of polymorphism.
2 Complete the subclass declaration
class Circle ____ Shape {
double area() { return Math.PI * r * r; }
}
class Circle extends Shape {
double area() { return Math.PI * r * r; }
}
Explanation: extends declares class inheritance.
3 Match the polymorphism concepts
| Term | Meaning |
|---|---|
virtual |
Default method behavior in Java |
override |
Redefining a method in a subclass |
extends |
Declares class inheritance |
super |
Parent class reference |