Static Polymorphism in Java with Program

Static Polymorphism, Static Binding, Compile time Polymorphism,
Method Overloading.


Polymorphism is one of the most important OOPS concept. The word "Polymorphism" means, "one name having many forms".

Please note, Polmorphism is just a concept that describes the ability of a method to behave differently at different situation, but is actually achieved either by Method Overloading(Static Polymorphism) or by Method Overriding(Dynamic Polymorphism).

More details on Polymorphism concept with example: here
 
Types of Polymorphism

  1. Static Polymorphism - Static Binding - Compile time Polymorphism - Method Overloading
  2. Dynamic Polymorphism - Dynamic Binding - Run time Polymorphism - Method Overriding  
Lets understand Static Polymorphism in more details with example.
Static Polymorphism



Before going into details of Static Polymorphism, lets first understand,
What Method Overloading means, Why it is used and What it is the importance of it?

Method Overloading.

Say for example, you go to bank for checking the account balance and forgot to carry your bank account number. what will happen? Definitely, bank representative will ask for your other options like first name, DOB or It will ask for your Permanent account number etc.
It means bank has provision to fetch your account details by multiple ways, So they need to write methods someway like below
  1. getCustomerByFirstNameAndDOB(String firstName, Date dob) { .... }
    Get the customer by First name and DOB.
  2. getCustomerByAccountNumber(long accountNumber)  { .... }
    Get the customer by bank account number.
  3. getCustomerByPANNumber(String panNumber)  { .... } Get the customer by Permanent Account Number.
  4. getCustomerByFirstNameLastNameAndDOB(String firstName, String lastName, Date dob) {} Get the customer by first name, last name and DOB.
Disadvantage: 
Now, as a developer, Imagine how many methods you need to remember and which to call for each scenario like,
  1. when customer knows only his PAN number, 
  2. when customer knows his first name, last name and dob, 
  3. when customer knows only his account number etc.
This adds more complexity when number of combinations by which you can fetch customer grows.
 Also at one point it would be difficult to maintain such methods and is less intutive.

Solution: This problem is solved using "Method Overloading".
All the above 4 methods we wrote has common purpose of getting the customer details, so why not method name should be "getCustomerDetails" and the developer has has to remember only one method getCustomerDetails in all the scenario.

So we can give common name to all the 4 methods and make them differ by parameters they take,
  1.  getCustomerDetails(String firstName, Date dob) { .... }
    Get the customer by his First name and DOB.
  2. getCustomerDetails(long accountNumber)  { .... } Get the customer by bank account number.
  3. getCustomerDetails(String panNumber)  { .... } Get the customer by Permanent Account Number.
  4. getCustomerDetails(String firstName, String lastName, Date dob) {} Get the customer by first name, last name and DOB.
Now, developer has to remember only one method "getCustomerDetails" and simply pass on the parameter by which you want to get customer.

Example: If you want to get customer details by PAN number, you need to call, getCustomerDetails("ABC1234567") and this will call method "getCustomerDetails" taking one parameter as String, which is present at number 3 above.
So this way of writing the multiple methods with same name but differ in parameters is called Method Overloading and methods are known as Overloaded methods.
Advantage:
  1. without Method Overloading, developer needs to remember many method names.
    With
    Method Overloading, developer needs to remember only one method name.
  2. When number of overloaded method grows, Method overloading increases the readability of the program.

Polymorphism

Lets have a quick look on what Polymorphism means, what does "one name having many forms" literally means?
  
In Java, there may be situation where you need to write multiple methods with same name (because they all do same job as we saw above) but they act/behave differently based on the parameters supplied.

Example:
  1. getArea(int radius) { return 3.14 * radius * radius; } used to calculate area of Circle.
  2. getArea(int length, int breadth) { return length * bredth; } used to calculate area of Rectangle.

If you look at above two method names "getArea", they both are doing same job of calculating area, so given only name, you cannot say, whether method is used to calculate area of circle, rectangle, triangle, pentagon etc, but Parameters supplied to the method will give the exact meaning to the method. whether it is used to calculate area of circle, rectangle etc because (method name + parameter supplied) will make each method unique.

Method with same name is used to calculate the area of Circle.
Method with same name is used to calculate the area of Rectangle and so on,
Method with same name "getArea" exhibits different behaviour based on parameter supplied, so this is what Polymorphism means "Same Name Multiple Behaviour/Forms."
 
For more details on Polymorphism concept with example: here


Method Overloading
Method with same name but differ in Parameter list is called Method Overloading. 
Note: 
In a class, if two or more methods have same name then they must differ in parameter list for valid Method overloading.
Return type and Exception thrown by method doesn't take part in Method Overloading.
There are many tricky questions on Method overloading which you may face during Interviews, 
There is separate post on this Method Overloading Interview Questions in Java


Classic example of Method Overloading in JDK API,

You might have used "System.out.println()" method and passed int, float, String, Object etc as a parameter like,
  1. System.out.println(10) -> 10
  2. System.out.println("hello") -> hello
  3. System.out.println(50.5) -> 50.5
Same method name println(), can print integer, float, String etc. this happens with method overloading because "println" method is overloaded.
Have a look below to see how many println methods are present,

If you look at above println methods, they all are doing same job of printing data, 
Name of the metod is same "println", but it used to print integer, float, double, object etc.
Same method name but so many behaviours this is called Polymorphism.Same method name but differ in parameter so is called Method overloading.
Just to give you idea how helpful method overloading is, Imagine the pain you need to go to if there are separate metods to print integer, float, double, object etc. you need to remember each method.
but with overloaded method, you need to remember only one method name "println" and don't care about what parameter you are passing and simply calls,
"System.out.println(Whatever data you want to print)"


Why is called Static Polymorphism OR  Static Binding OR Compile time Polymorphism.

Lets take same example as of above and try to understand this. 
we have four overloaded methods as shown below,
  1.  getCustomerDetails(String firstName, Date dob) { .... }
    Get the customer by his First name and DOB.
  2. getCustomerDetails(long accountNumber)  { .... } Get the customer by bank account number.
  3. getCustomerDetails(String panNumber)  { .... } Get the customer by Permanent Account Number.
  4. getCustomerDetails(String firstName, String lastName, Date dob) {} Get the customer by first name, last name and DOB.
When we have multiple methods with same name, how JVM will come to know which method to call as JVM will found multiple methods with same name?

When a call to above method is made like this ' getCustomerDetails("ABC1234567"); '. logically first thing what need to be done is searching for the method with name getCustomerDetails and call that method, but in this case we have four methods with same name.
So to resolve this ambiguity, before even JVM knows about this, at compiler level only method names are made unique by the number of parameters supplied.

When method names are same, there should be something which make each method unique and if you note that is the parameters they take.

So Java compiler will check the parameter list of the methods and mark the method call to method definition at compile time itself so JVM doesn't need to take pain and it simply calls the marked method which compiler mentioned.

In above case, when someone calls ' getCustomerDetails("ABC1234567"); ', it has only one parameter of type String as it is written in double quotes.

So what COMPILER will search for is, a method having name "getCustomerDetails" and which takes one parameter of type String. when this two factors are combined that is name and parameter list it will definitely find a unique method which in our case is below one,
getCustomerDetails(String panNumber){
....
}

Any method call which is resolved at COMPILER level is called static polymorphism and method call which is resolved at JVM level is called dynamic polymorphism.
So in case of Method Overloading, method call to method definition is resolved at COMPILER level that is why it is called Static Polymorphism.

You may also like to see


When to use interface and abstract class in Java?

Real time example of abstract class and interface in Java project.

Java Multithreading and Concurrency Interview Questions and Answers with Example

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Method Overriding Rules In Java

How is ambiguous overloaded method call resolved in java?

Method overriding and Method hiding Interview Question in Java

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment