Friday 6 November 2015

What is overloading method in java ? : The Pictorial Way

Overloading Method :

A method with same name but with different argument list is known as method overloading.
Below image will explain you in detail about method Overloading in java.

Method Overloading in Java
Rules for method Overloading in Java?
  1. Overloaded method name must be same.
  2. Overloaded method must have different argument list.
  3. Overloaded method can have different access specifier.
  4. Overloaded method can have different return type.
  5. Overloaded method can be in same class or different class.
  6. Overloaded method can declare a broader checked exception.
Why reference type determines which method to invoke in overloading ?

Have a look at below image and than read the explanation explanation following it.

Accessing Overloaded Method in Java

In overloading reference type determines, which method to invoke and not the object type, this is because method overloading is a compile time polymorphism and so method binding is done at compile time. Therefore at run time reference is pointing to which object dose not matter for overloaded method.


Why changing only a return type is not legal in overloading?
Why we cannot only change return type and keep the argument list same in overloading?

This is because in overloading compiler binds a method to instance based on the argument list, and if the argument list of two methods is same it will cause a ambiguity about which method to invoke.

When to use method overloading?
You can use method overloading when you don't want user to restrict on datatype of data he is passing as argument, or when you want to take different action depending on data passed by user.

For example:

Class int overloadedExample {
    public int add(int a, int b)
      {
              return a + b;
       }

  public String add(String a, String b)
      {
              return a + b;
       }
}

In the above example, when user will invoke add(10,20) he will get the addition of provided numbers, on the other-hand if user invokes add("Hello","World") he will get the concatenated string. 

Can we overload main method? 
Yes we can overloaded main method, but JVM will always invoke public static void main(String[] args).

No comments:

Post a Comment