Jump to content


 


Register a free account to unlock additional features at BleepingComputer.com
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Click here to Register a free account now! or read our Welcome Guide to learn how to use this site.

Photo

How Method Overloading in Java works and Examples


  • Please log in to reply
No replies to this topic

#1 Chaktty

Chaktty

  • Members
  • 4 posts
  • OFFLINE
  •  

Posted 10 September 2017 - 10:04 AM

As a java programmer, methods can be overloaded. Overloading means that the same method name can be used multiple times in a class. Overloading often occurs with constructors or conversion methods.
To allow overloading, at least one of the following requirements must be met:
1. The data type of one or more passing parameters is different from the other same name methods.
2. The number of passing parameters is different.
Here are some examples from the Java class Library java. lang. Math
public static int abs (int)
public static float ABS (float)
public static long ABS (long)
public static double abs (double)
The ABS method returns the absolute value of the passed parameter. Because all methods should provide the same functionality, the method is overloaded. Only the data type of the passed parameter is different. For example, for a mathematical method that always do the same thing, you do not have to choose a new name for each data type.

Other examples of overloaded methods include:
public void setvalues (int value1, int value2)
public void setvalues (int value1, int value2, int value3)
public void setvalues (int value1, float value2)
public void SetValue (int value1, short value2)
public void setvalues (int value1, string value2)
public void Setvalues (float value1, int value2, int value3)
public void setvalues (int value1, byte [] value2, int value3)
A constructor can also be overloaded in this manner.

Overloaded Constructor Example:
public class Person
{
Attributes
String name;
string First name; Person ()
{
/* Default constructor */
}
1. Overloaded constructor
Person (string name)
{
THIS.name = name;
}
2. Overloaded constructor
Person (string name, string first name)
{
THIS.name = name;
this. First name = First name;
}
}

BC AdBot (Login to Remove)

 





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users