Polymorphism
Polymorphism is an object-oriented programming concept that lets one interface be used for different underlying forms. The same method call can behave differently depending on the object it is called on, so code can work with a general type while each specific type supplies its own behaviour.
There are two kinds: compile-time polymorphism, achieved through method overloading (same method name, different parameters), and run-time polymorphism, achieved through method overriding, where a subclass provides its own version of a method declared in its parent class or interface.
package in.ihelpyou;
class Shape {
double area() { return 0; }
}
class Circle extends Shape {
double r = 2;
@Override
double area() { return Math.PI * r * r; }
}
class Square extends Shape {
double side = 3;
@Override
double area() { return side * side; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(), new Square() };
for (Shape s : shapes) {
System.out.println(s.area()); // each object runs its own area()
}
}
}