Thursday 5 April 2012

Method Overloading

Basically polymorphism is classified in two types in Java.

1. Static Polymorphism
2. Dynamic Polymorphism

1. Static Polymorphism (Method Overloading):
          Defining 2 methods with same name but different method signatures in a class is known as Method Overloading.

        Class MethodOverload {
                 public void overload() {
                      System.out.println("Overloaded method");
                 }
                 public int overload( int i) {
                      System.out.println("Overloading method" + i);
                      // requirement specific logic is written as above line
                      return i;

                 }
                 public static  int overload(String s) {
                      System.out.println("Overloading method" + s);
                      // requirement specific logic is written as above line
                      return s;

                 }
         }

        Class Test{
                 public static void main(String[] args) {
                      MethodOverload   load = new MethodOverload();
                      load.overload();
                      load.overload(5);
                      load.overload("hello");
                 }

         }

Output:
Overloaded method
Overloading method5
Overloading methodhello

Conditions for method overloading are:
1. Atleast method arguments should be different if you are using a single argument (as above).
2. Atleast method arguments order should be different if there are more than 1 argument.
3. Atleast number of method arguments should be different.

Important Note:
1. Method return type is not a part of Overloading.
2. Access Modifiers are also not a part of Overloading.
3. We can have static methods overloaded too.


But why overloading is considered as static polymorphism?
     Because the method invocation call is binded to the respective method at compile time itself by the compiler. Here as the binding is happening at compile time it is also know as early binding or static binding or compile time binding.

4 comments:

  1. Good post, nice and clear.just to add, private, static and final methods are bonded statically on compile time.
    source: Difference between static vs dynamic binding in java

    ReplyDelete
  2. http://myniftyfuturecalls.blogspot.in/

    ReplyDelete
  3. Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
    java training in chennai |
    best java institute in chennai

    ReplyDelete