In this article we will see 'What is method overloading in Java', and how to use it with example.

Method overloading in Java is when two or more methods in same class or in a sub class has same name, same return type and follows either or both of the following condition:
1) Number of arguments are different
2) Type of arguments are different.

Method overriding is also referred to as runtime polymorphism.
class Calculate {
	public long add(int a, int b) {
		return a + b;
	}

	public long add(int a, int b, int c) {
		return a + b;
	}

	public long add(int a, int b, long c) {
		return a + b + c;
	}
}

class CalculateAgain extends Calculate {
	public long add(int a, long b, long c) {
		return a + b + c;
	}
}
In the example above all four methods with name 'add()' are overloaded.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

Method overloading keeps the code simple, as can be seen in the example above all the 4 methods are doing the same work "addition", so it will be a ugly practice to give them different names and hard to remember the names when calling for different type of arguments.

In this article we have seen 'What is method overloading in Java', and how to use it with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java