The following example code demonstrates How to Perform Runtime Polymorphism in Java.
Create a class Shape containing three methods – area(), draw(), and erase(). Also, create its three subclasses – Circle, Rectangle, and Triangle. Demonstrate the runtime polymorphism using these classes.
Here’s an example of creating a class Shape
and its subclasses Circle
, Rectangle
, and Triangle
in Java.
abstract class Shape {
abstract void area();
void draw() {
System.out.println("Drawing Shape");
}
void erase() {
System.out.println("Erasing Shape");
}
}
class Circle extends Shape {
void area() {
System.out.println("Calculating area of Circle");
}
void draw() {
System.out.println("Drawing Circle");
}
void erase() {
System.out.println("Erasing Circle");
}
}
class Rectangle extends Shape {
void area() {
System.out.println("Calculating area of Rectangle");
}
void draw() {
System.out.println("Drawing Rectangle");
}
void erase() {
System.out.println("Erasing Rectangle");
}
}
class Triangle extends Shape {
void area() {
System.out.println("Calculating area of Triangle");
}
void draw() {
System.out.println("Drawing Triangle");
}
void erase() {
System.out.println("Erasing Triangle");
}
}
And here’s an example of using these classes to demonstrate runtime polymorphism.
class Test {
public static void main(String args[]) {
Shape s;
s = new Circle();
s.area();
s.draw();
s.erase();
s = new Rectangle();
s.area();
s.draw();
s.erase();
s = new Triangle();
s.area();
s.draw();
s.erase();
}
}
In this code, the class Shape
is defined as an abstract class with three methods area()
, draw()
, and erase()
. The subclasses Circle
, Rectangle
, and Triangle
extend the Shape
class and provide their own implementation of the area()
method. The class Test
uses the references of Shape
class to hold objects of its subclasses, which demonstrates runtime polymorphism. When the methods area()
, draw()
, and erase()
are called using the references of Shape
, the JVM calls the corresponding methods in the actual objects.