Polymorphism in Java — Java Technical Interview Questions & Answers
Polymorphism in Java
Polymorphism in Java
- Polymorphism means one name, many forms. Compile-time: method overloading — same name, different parameters. Runtime: method overriding — parent reference, child object.
- Classic line: Animal a = new Dog(); a.sound(); calls Dog’s version at runtime. That lets you write flexible code. Add a new child class without rewriting all callers.
- Don’t mix the two definitions. Overloading is decided at compile time. Overriding is decided at runtime. Give one example each.
- Let's take this on the board with one tiny Main class — no extra files. Polymorphism in Java — output: Meow. Reference type is Animal, real object is Cat — runtime polymorphism. Start from main, go line by line, and stop at each print. That output is the proof for Polymorphism.
Technical Interview Tip: Overloading vs overriding — two examples, two timings.
Code Examples for Polymorphism in Java
Example
class Animal {
void sound() { System.out.println("Some sound"); }
}
class Cat extends Animal {
@Override
void sound() { System.out.println("Meow"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Cat();
a.sound();
}
}Polymorphism in Java — output: Meow. Reference type is Animal, real object is Cat — runtime polymorphism.
How to Explain Polymorphism in Java to an Interviewer
What is polymorphism?
One name, many forms
What is compile-time polymorphism?
Overloading
What is runtime polymorphism?
Overriding Parent ref + child object
What does Animal a = new Dog(); a.sound(); call?
Dog’s sound() Decided at runtime