Polymorphism
In the context of object-oriented programming (OOP), polymorphism refers to the ability of an object to take on different forms and to be treated as an object of its own class or as an object of any of its parent classes or implemented interfaces.
Polymorphism allows objects to be used in a generic way, regardless of their specific implementations. This enables code reusability and flexibility in designing complex systems.
For example, consider a scenario where you have different sports objects, such as basketball, soccer, and tennis. These sports have different implementations of the play()
method, but they all share a common interface defined by an abstract class Sports
.
TEXT/X-JAVA
1abstract class Sports {
2 public abstract String getName();
3 public abstract void play();
4}
xxxxxxxxxx
51
}
public class Main {
public static void main(String[] args) {
// Create an array of different sports objects
Sports[] sports = new Sports[3];
sports[0] = new Basketball();
sports[1] = new Soccer();
sports[2] = new Tennis();
// Iterate over the array of sports objects
for (Sports sport : sports) {
System.out.println("Playing " + sport.getName());
sport.play();
}
}
}
abstract class Sports {
public abstract String getName();
public abstract void play();
}
class Basketball extends Sports {
public String getName() {
return "Basketball";
}
public void play() {
System.out.println("Bouncing the basketball");
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment