What is runtime polymorphism in Java?
One way you can achieve Runtime polymorphism in java is by Method Overiding. Lets check the code followed by explanation.
Source code (Animal.java)
Source code (Animal.java)
/** * @author javaQuery * @date 7th November, 2017 * @Github: https://github.com/javaquery/Examples */ public class Animal { public void run(){ System.out.println("Animal is running..."); } }Source code (Dog.java)
/** * @author javaQuery * @date 7th November, 2017 * @Github: https://github.com/javaquery/Examples */ public class Dog extends Animal{ @Override public void run() { System.out.println("Dog is running..."); } }Source code (Cat.java)
/** * @author javaQuery * @date 7th November, 2017 * @Github: https://github.com/javaquery/Examples */ public class Cat extends Animal{ @Override public void run() { System.out.println("Cat is running..."); } }Source code (Horse.java)
/** * @author javaQuery * @date 7th November, 2017 * @Github: https://github.com/javaquery/Examples */ public class Horse extends Animal{ }Source code (RuntimePolymorphismExample.java)
/** * Example demonstrate Runtime Polymorphism. * * @author javaQuery * @date 7th November, 2017 * @Github: https://github.com/javaquery/Examples */ public class RuntimePolymorphismExample { public static void main(String[] args) { // super-class Animal animal = new Animal(); animal.run(); /***********************************************/ /* sub-class `Dog` */ /***********************************************/ Dog dog = new Dog(); dog.run(); animal = dog; /** * animal.run() * It will call referenced object's `run()` method. * In this case, object of `Dog` class is referred. */ animal.run(); // runtime polymorphism /***********************************************/ /* sub-class `Cat` */ /***********************************************/ animal = new Cat(); /** * animal.run() * It will call referenced object's `run()` method. * In this case, object of `Cat` class is referred. */ animal.run(); // runtime polymorphism /***********************************************/ /* sub-class `Horse` */ /***********************************************/ animal = new Horse(); /** * animal.run() * It will call referenced object's `run()` method. * However in this case, object of `Horse` doesn't contain implementation of `run()` so method * from the super-class `Animal#run` will be called. */ animal.run(); // runtime polymorphism } }Output
Animal is running... Dog is running... Dog is running... Cat is running... Animal is running...
0 comments :