Polymorphism
A parent type variable can hold any child object. When you call an overridden method, Java runs the version of the actual object. This lets you write code that works with many related classes.
Example
class Shape {
double area() { return 0; }
}
class Square extends Shape {
double side;
Square(double s) { side = s; }
@Override double area() { return side * side; }
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.round(Math.PI * r * r * 100) / 100.0; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Square(3), new Circle(2) };
for (Shape s : shapes) {
System.out.println(s.area());
}
}
}Result
9.0 12.57
Exercise
Which annotation marks a replaced method?
void speak() {}Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.