OOPS WITH JAVA 1
POLYMORPHISM
The word “poly” means “many” and “morphism” means “form”.
The word "Polymorphism" means "many forms".
It is a greek word whose meaning is “same object having different behaviour.”
In Java, polymorphism allows one interface to be used for different underlying forms (data
types or behaviors).
TYPES OF POLYMORPHISM:
Type Also Known As Resolved At
Compile-time Method Overloading Compile Time
Polymorphism
Runtime Polymorphism Method Overriding Runtime
COMPILE TIME POLYMORPHISM:
● When multiple methods have the same name but different parameters.
● Polymorphism which exists at the time of compilation.
● Also called early binding or static polymorphism.
● Method overloading is used here
#We can have different return type of method,but name of method should be same and
parameter should be different.
Overloading means whenever a class contain more than one method with same name
and different types of parameters.
class Calculator {
void add(int a, int b)
{System.out.println("Sum (int): " + (a + b));}
void add(double a, double b)
{ System.out.println("Sum (double): " + (a + b));}
void add(int a, int b, int c)
{System.out.println("Sum of 3 numbers: " + (a + b + c));}
public class Test {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(5, 3);
calc.add(5.2, 3.8);
calc.add(1, 2, 3);
RUNTIME POLYMORPHISM:
● When a subclass provides a specific implementation of a method that is already
defined in its superclass.
● Polymorphism which exists at the time of execution of program.
● Method overriding is used here.
Overriding means whenever super and sub class contain method with same name and
same type of parameter.
#We can’t perform method overriding without inheritance.
It first checks whether the superclass have same method or not,if not it generates error.
If @Override is not present,then it calls superclass method.
class Animal {
void sound()
{ System.out.println("Animal makes a sound");}
class Dog extends Animal {
@Override
void sound()
{System.out.println("Dog barks");}
class Cat extends Animal {
@Override
void sound()
{ System.out.println("Cat meows");}
public class Test {
public static void main(String[] args) {
Animal a1 = new Dog(); // Upcasting
Animal a2 = new Cat();
a1.sound(); // Output: Dog barks
a2.sound(); // Output: Cat meows
COMPILE TIME VS RUNTIME
POLYMORPHISM:
Feature Compile-Time Polymorphism Runtime Polymorphism
Also Known As Method Overloading Method Overriding
Resolved When? Compile Time Runtime
Flexibility Less More
Inheritance Required? No Yes