Method OverLoading in Java - Java @ Desk

Monday, March 3, 2014

Method OverLoading in Java

Method OverLoading in Java

In the last post, we seen Method Overriding in Java which states that overriding is decided at runtime.

Compared to overriding, overloading is decided at the compile time.

Overloading in java occurs when a methods in a class have a same method name and same return type but there is a difference in:
1) Number of Arguments
2) Types of Arguments
3) Same number of arguments but with different types
4) Different number of arguments but with different types

Overloading in java also occurs in case of Inheritance, where the method is overloaded in the child or sub class.

Overloading in java cannot take place if only the return type is changed but the number of arguments and type of arguments remain the same because in this case the compiler won't be able to know which method to call.

Can static method overload?

Yes static method can be overloaded. Static methods anyways belongs to class and they are called using the class name and by not using the class object.

 
Can final method overload?

Yes final method can be overloaded.

 
Sample implementation of overloading

In the below implementation, there is a method getBankBalance where the bank balance is loaded either by accId or accName or both using the overloading implementation. In the example, overloading is done using :
1) Different type of argument
2) Different number & type of argument
3) Overloading of static & final methods to get credit report and insurance

package com.overload;

public class Overload {

 public void getBankBalance(Integer accId) {

 }

 public void getBankBalance(String accName) {
  System.out.println("Overloading using different type of argument");
 }

 public void getBankBalance(Integer accId, String accName) {
  System.out
    .println("Overloading using different number & type of argument");
 }

 public static void getCreditReport() {
  System.out.println("Static Method");
 }

 public static void getCreditReport(String string) {
  System.out.println("Overload Static Method - " + string);
 }

 public final void getInsurance() {
  System.out.println("Final Method");
 }

 public final void getInsurance(String string) {
  System.out.println("Overload Final Method - " + string);
 }
 
 public static void main(String args[]) {
  Overload.getCreditReport();
  Overload.getCreditReport("String");

  Overload overload = new Overload();
  overload.getInsurance();
  overload.getInsurance("String");
 }
}


To download source, click here






No comments:

Post a Comment