Polymorphism
·
Mohammad-Ali Bandzar
An introduction to polymorphism with Java.
Polymorphism is the ability of an object to take on many forms. In Java this happens when we create multiple classes that refer to/depend on each other to function. Since methods can be inherited from other classes, we can reuse methods saving us development time and making our code more readable.
class Animal {
public void sound() {
System.out.println("...");
}
}
class Bird extends Animal {
public void sound() {
System.out.println("Chirp Chirp");
}
}
class Cat extends Animal {
public void sound() {
System.out.println("Meow");
}
}
class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Animal cat = new Cat();
Animal bird = new Bird();
animal.sound(); // call sound
bird.sound(); // call sound
cat.sound(); // call sound
Animal a = cat; // Up casting
a.sound();
Cat c2 = (Cat) a; // Down Casting back to its original
c2.sound();
}
}
THANKS FOR READING