What is Polymorphism in Java with example - CodeByAkram

What is Polymorphism in Java with example


What is Polymorphism in Java with example.

Polymorphism is one of the most important concept of OOPS that means "one object having many forms".

Polymorphism is a Greek word which means "Many Forms", Polymorphism = (Poly + Morphism) = Many + Forms.

 Lets understand above line in more details with example.

Every concept of OOPS also exist in Real Life, so for better understanding lets first understand real life example of Polymorphism.


Real Life example

There are many English words when used without context will have multiple meanings.
Example:

If I don't give you context and simply say word, you will not able to exactly tell what it is used for.

bear:
    • bear can be used to represent a mammal "The black bear". 
    • bear can also be used in context of pain like "I cannot bear his constant criticism".
Similarly,

close:
    • close can be used in context of opposite of far like "Please close the window".
    • close can also be used in context of opposite of open like "Please close the door".
So many words in English has multiple meanings that is "same word but multiple meanings".
Isn't it matching with our Polymorphism definition "same object many forms"!!!


In Java

Similarly in Java, there can be a situation where we need to write more than one methods with same name (because they all do the same job) but they behave differently based on the parameters supplied.

Lets take an example:


  1. getSum(int a, int b) { return a+b; } used to calculate the sum of two integer number.
  2. getSub(int a, int b, int c) { return a+b+c; } used to calculate the sum of three integer number.

If you look at above two method names "getSum", they both are doing same job of calculating sum of integer numbers, so given only name, you cannot say, whether method is used to calculate sum of two or three numbers. but you will definitely get a broad idea that method is used to calculate the sum.

Parameters supplied to the method will give the exact meaning to the method. whether it is used to calculate sum of two numbers or three numbers.

We can achieve Polymorphism in Java by,
  1. Method Overloading
  2. Method Overriding.


Another example of Polymorphism,
We use "System.out.println()" method and passed int, float, String, Object etc as a parameter like,
System.out.println(10) -> 10
System.out.println("hello") -> hello
System.out.println(50.5) -> 50.5
same method name println(), can sometime print integer, sometime float, sometime String etc.

Internally there are multiple println() method written as shown below,



No comments:

Post a Comment