Posted on
Polymorphism in Java – Understanding Compile-time and Runtime Behavior
Polymorphism in Java is one of the core concepts of Object-Oriented Programming (OOP). It allows us to perform a single action in different ways. Polymorphism means"many forms". In simple terms, it allowsone interface to be used for multiple implementations, making our code flexible and reusable.
Types of Polymorphism in Java
In Java, polymorphism is classified into two main types:
- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
1. Compile-time Polymorphism (Method Overloading)
Compile-time polymorphism occurs when the method call is resolved atcompile time. The most common example of this isMethod Overloading.
What is Method Overloading?
If a class has multiple methods with thesame name but different parameter lists (different number or type of parameters) it is calledMethod Overloading.
Example:
classCalculator{intadd(inta,intb){returna+b;}doubleadd(doublea,doubleb){returna+b;}}publicclassMain{publicstaticvoidmain(String[]args){Calculatorcalc=newCalculator();System.out.println(calc.add(5,10));// calls int versionSystem.out.println(calc.add(5.5,10.2));// calls double version}}
Why use it?
- Increasesreadability of the program
- Same method name with different argument list iseasy to remember
Ways to Achieve Overloading
- By changing thenumber of arguments
- By changing thedata type of arguments
2. Runtime Polymorphism (Method Overriding)
Runtime polymorphism, also known asDynamic Method Dispatch, is achieved throughMethod Overriding. In this case, the method call is resolvedat runtime, not at compile time.
What is Method Overriding?
If asubclass (child class) providesspecific implementation of method that is already defined in itsparent class, it is calledMethod Overriding.
Rules for Overriding:
- The method in the child class must have the same name, return type, and parameters as in the parent class.
- It requires inheritance (using
extends
).
Example:
classAnimal{voidsound(){System.out.println("Animal makes a sound");}}classDogextendsAnimal{@Overridevoidsound(){System.out.println("Dog barks");}}publicclassMain{publicstaticvoidmain(String[]args){Animala=newDog();// Upcastinga.sound();// Output: Dog barks (resolved at runtime)}}
Why use it?
- To provide a specific implementation in the child class
- To achieve runtime polymorphism.
Conclusion
- Polymorphism makes Java programs more flexible, extensible, and easier to maintain.
- UseOverloading for compile-time decisions and code clarity.
- UseOverriding for dynamic behavior and runtime flexibility.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse