Program to show Polymorphism in Java

Polymorphism means one name, many forms.
There are 3 distinct forms of Java Polymorphism;
* Method overloading (Compile time polymorphism)
* Method overriding through inheritance (Run time polymorphism)
*Method overriding through the Java interface (Run time polymorphism)
Polymorphism allows a reference to denote objects of different types at different times during execution. A super type reference exhibits polymorphic behavior, since it can denote objects of its subtypes.
Example: 1
interface Shape {
public double area();
public double volume();
}
class Cube implements Shape {
int x = 10;
public double area( ) {
return (6 * x * x);
}
public double volume() {
return (x * x * x);
}
}
class Circle implements Shape {
int radius = 10;
public double area() {
return (Math.PI * radius * radius);
}
public double volume() {
return 0;
}
}
public class PolymorphismTest {
public static void main(String args[]) {
Shape[] s = { new Cube(), new Circle()
};

Output
The area and volume of class Cube is 600.0 , 1000.0
The area and volume of class Circle is 314.1592653589793 , 0.0

The methods area() and volume() are overridden in the implementing classes. The invocation of the both methods area and volume is determined based on run time polymorphism of the current object as shown in the output.

No comments:

Google Search