Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

Method Overloading in Java

Method overloading is a mechanism where a class have multiple methods by same name but different parameters, it is known as Method Overloading. Method overloading is one of the ways through which java supports polymorphism.
Method overloading can be done by "changing number of arguments" or "by changing the data type of arguments." If two or more method have same name and same parameter list but differs in return type are not said to be overloaded method

Ex : Method overloading By Changing the data type of arguments

public class Calculator  {

	public void sum(int a,int b) {
		System.out.println("Sum ="+(a+b));
	}
	
	public void sum(double x,double y) {
		System.out.println("Sum ="+(x+y));
	}
	
	public static void main(String[] args)  {
		Calculator opr=new Calculator();
		opr.sum(10,10);
		opr.sum(20.0,20.0);
	}
 }

Output :

Sum = 20
Sum = 40.0

In the above example - method sum() has been overloaded based on the data types of arguments We have two definition of method sum(), one with int argument and another with double arguments.

Ex : Method overloading By changing number of arguments

public class Calculator  {

	public void sum(int a,int b) {
		System.out.println("Sum ="+(a+b));
	}
	
	public void sum(int x,int y,int z) {
		System.out.println("Sum ="+(x+y+z));
	}
	
	public static void main(String[] args)  {
		Calculator opr=new Calculator();
		opr.sum(50,50);
		opr.sum(100,100,100);
	}
 }

Output :

Sum = 100
Sum = 300

In the above example - method sum() has been overloaded based on the number of arguments We have two definition of method sum(), one with two argument and another with three arguments.

Why Method Overloading is not possible by changing the return type of method ?

In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let see why

public class Invite  {

	public String sayHello(String wish) {
		------------
		------------
		return "hello";
	}
	
	public boolean sayHello(String wish) {
		
		------------
		------------
		return true;
	}
	
	public static void main(String[] args)  {
		Invite in=new Invite();
		in.sayHello("Good Morning");//Compile Time Error
	}
 }

Here how can java determine which sayHello() method should be called