(Java)Overloading

Function overloading or method overloading is a feature found in various programming languages such as Ada, C++, C#, D, Java, that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. It is simply defined as the ability of one function to perform different tasks.
For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn’t know which of the two methods to use.
Another appropriate example would be a Print(object O) method. In this case one might like the method to be different when printing, for example, text or pictures. The two different methods may be overloaded as Print(text_object T); Print(image_object P). If we write the overloaded print methods for all objects our program will “print”, we never have to worry about the type of the object, and the correct function call again, the call is always: Print(something).

Example :

class Overload {

void test(int a) {
System.out.println("a: " + a);
}

void test(int a, int b) {
System.out.println("a and b: " + a + "," + b);
}

double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}

class MethodOverloading {
public static void main(String args[]) {
Overload overload = new Overload();
double result;
overload.test(10);
overload.test(10, 20);
result = overload.test(5.5);
System.out.println("Result : " + result);
}
}
<pre> 

Save As Name : MethodOverloading.java

Compile :

Advertisements

Published by

jarcode

hello I am jarcode

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s