Run Time Polymorphism Example in Java
On this page (8sections)
Introduction
Run Time Polymorphism is a classic Java console program that demonstrates the concept with complete source code and sample output. Object-oriented programming models real entities with classes, objects, inheritance and polymorphism.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Run Time Polymorphism Example Program
class ClassA{
public void disp(){
System.out.println ("I am inside Class A");
}
}
class ClassB extends ClassA{
public void disp(){
System.out.println ("I am inside Class B");
}
}
public class RunTimePolymorphismDemo{
public static void main (String args []) {
ClassA obj1 = new ClassA();
ClassA obj2 = new ClassB();
obj1.disp();
obj2.disp();
}
}
Sample Output
I am inside Class A
I am inside Class B
When to use
Use OOP examples when modelling entities with state and behaviour in larger applications.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
ClassA obj1 = new ClassA();updates a variable used in the calculation or output. -
ClassA obj2 = new ClassB();updates a variable used in the calculation or output. -
Compare your console output with the sample output for Run Time Polymorphism to confirm the program behaves correctly.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.