Polymorphism
Polymorphism means "many forms." In Java, it refers to the ability of the same method name or the same object reference to behave differently depending on the actual object or the arguments involved.
1. What is Polymorphism?
Polymorphism means "many forms." In Java, it refers to the ability of the same method name or the same object reference to behave differently depending on the actual object or the arguments involved.
2. Why is it used?
It allows one consistent interface (like a single method name) to work correctly across different types of objects, without needing separate, uniquely named methods for every single case.
3. Real-Life Example
Think of the word "draw" — drawing a circle, drawing a square, and drawing a triangle are all different actions, but they're all referred to using the same general word "draw." Polymorphism lets code use one common name while behaviour still adapts to the specific case.
4. Syntax
javaParentClass ref = new ChildClass(); // reference type vs actual object type ref.someMethod(); // runs ChildClass's version, if overridden
5. Example Program
javaclass Shape { void draw() { System.out.println("Drawing a shape"); } } class Circle extends Shape { void draw() { System.out.println("Drawing a circle"); } } public class PolymorphismDemo { public static void main(String[] args) { Shape shape = new Circle(); shape.draw(); // runs Circle's version } }
Output:
Drawing a circle6. Key Points to Remember
- Polymorphism appears in Java mainly in two forms: method overloading (compile-time) and method overriding (runtime).
- Runtime polymorphism happens through overriding, decided based on the actual object, not the reference type.
- It's a core Object-Oriented concept, frequently tested in interviews with practical code examples.