By:Mohammad-Ali Bandzar | May 9 2019
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 re use methods saving us development time and making our code more readible.
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
credits:Mrs.Krastavas pickup folder