Method Overloading in Java

Method Overloading is the concept of writing multiple methods with the same name. Here the common characteristic is only the name. Parameters must be different. Return type can be anything. Also note that method overloading is within same class or inherited class. Look at the below points on how to overload a method.

  • All the methods must have the same name. It is the basic principle for overloading a method. Same method with different parameters are considered as overloaded.
  • You can change the number of parameters to each method
  • You can change the data type of the methods
  • If you change only the return type of a method, it is not considered as overloaded. You have to change the parameters.
    Implicit promotion happens when you call a overloaded method. If there is no matching found, it will check for the possible implicit promotion and call the suitable method. For example if you call a method with parameter of int data type, if there is no method with int data type but there is matching long data type, then that will be called.
  • The implicit type promotion happens as like this:
    • byte -> short -> int -> long
    • byte -> short -> int -> float -> double
    • char -> int -> float -> double
    • Char -> int -> long
  • In some cases, there will be a ambiguity for resolving the promotion if more than one matching methods are available. In that case compiler would throw error saying the ambiguity.

Overloading Example

package javabeat.net.core;

public class OverloadDemo {
	public void print(int i){
		System.out.println("Overloaded method : print(int)");
	}
	public void print(int i, int j, long k){
		System.out.println("Overloaded method : print(int,int,long)");
	}
	public void print(char i, int j){
		System.out.println("Overloaded method : print(char,int)");
	}
	public void print(int i, String str){
		System.out.println("Overloaded method : print(int,string)");
	}
	public void print(long i, int j){
		System.out.println("Overloaded method : print(int,string)");
	}
	public void print(int i, long j){
		System.out.println("Overloaded method : print(int,string)");
	}

	public static void main (String args[]){
		OverloadDemo demo = new OverloadDemo();
		demo.print(10);
		//This is ambiguious since method parameters not able to resolve the suitable method
		//demo.print(10,10);
		demo.print(10,"string");
		demo.print(10,10,10);

		//Implicit promotion of second parameter to int
		demo.print('a','b');
	}
}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*