Runtime Polymorphism
This program demonstrates runtime polymorphism.
Problem Statement
Write a Java program to show runtime polymorphism using method overriding.
Source Code
| 1 | class Animal { |
| 2 | void sound(){ System.out.println("Animal sound"); } |
| 3 | } |
| 4 | class Dog extends Animal { |
| 5 | @Override |
| 6 | void sound(){ System.out.println("Dog barks"); } |
| 7 | } |
| 8 | public class RuntimePolymorphism { |
| 9 | public static void main(String[] args) { |
| 10 | System.out.println("Eduinq Runtime Polymorphism"); |
| 11 | Animal a=new Dog(); |
| 12 | a.sound(); |
| 13 | } |
| 14 | } |
Program Output
Eduinq Runtime Polymorphism Dog barks
Explanation
Method overriding resolved at runtime. - JVM decides which method to execute based on object type. - This is runtime polymorphism, also called dynamic binding. Conclusion: Shows runtime polymorphism using overriding.