Encapsulation : Method Overloading
In this tutorial you will learn one of polymorphism concept that is method overloading with example in Java 7.
Method Overloading:
Method overloading, also called function overloading. It is one of polymorphism concept. You can define more than one method of same name within one class but the parameters declaration or return types are different.
Example :
Here we overloading method testValue() as
method name is same but parameter declaration and return type is different. In first
void testValue()
we are simply printing some text. In next void testValue(int a) printing int value of
a. In last int testValue(int a,int b) we are passing two arguments of int type and
returning int type sum of both numbers. So you can see we used same function name but each
time parameter declaration or return type is different. This is concept of method overloading.
class Overload { void testValue() { System.out.println("It is just a test"); } void testValue(int a) { System.out.println("It is int value : " + a); } int testValue(int a, int b) { return a + b; } } public class MethodOverloading { public static void main(String[] args) { Overload overload = new Overload(); overload.testValue(); overload.testValue(20); System.out .println("Sum of two numbers : " + overload.testValue(30, 40)); } }
Output :
It is just a test It is int value : 20 Sum of two numbers : 70