Understanding Polymorphism in Java: A Comprehensive Guide

polymorphism

  • Poly means =two
  • Morph=forms

If something exists in different forms called polymorphism.
In java if same method can perform different task called polymorphism.
In java polymorphism is considered into two versions.

  • Compile time polymorphism (Static binding (or) method
    overloading).
  • Run time polymorphism (Dynamic binding (or) method overriding).

Compile time binding (Static binding (or) method overloading):-

Means that the information required to call a function is available at compile time itself. It is achieved using “method overloading”.          

Method overloading:-

Two or more methods having same name but difference in “method signature” called method overloading.

Method signature:-

Method signature represents some difference in the method can be uniquely identified.

Example:-
1. The difference may be
    Sum(int a, int b)
    Sum (int a,int b, int c)
2. In the data types of parameters
    a. Sum (int a, int b)
    b. Sum (double a, double b)
3. In the sequence of parameters
    a. Display(int a, char b)
    b. Display(char a, int b)

Run time polymorphism (dynamic binding (or) method overriding):-

  • Runtime polymorphism is essentially referred as method overriding.
  • Method overriding is feature which you get when you implement inheritance in your program.

Method overriding:-

  • Writing two (or) more methods having same name and same signature called method overriding.

Casting object reference:-

We can cast one type of reference into another type of reference.

  1. Widening (or) up casting.
  2. Down casting (or) narrowing.

Widening (or) up casting:-

  • Super class reference can refer to sub class object.
  • Here implicit casting is done internally.
  • Class two references are converted into super class reference this is called up casting (or) widening.

Note:-

In this case we cannot call all the members, only methods which are in the super class can be called as the reference type is super class. If we try to call we get the compile time error.

Down casting (or) Narrowing:-

  • We cannot use sub class sub class reference to refer super class object.
  • We can cast super class reference as sub class reference type. This is called down casting (or) narrowing.
  • Here explicit cast is required.

Leave a Comment

Your email address will not be published. Required fields are marked *