Ex: If you have enough information. You can do the same task “telling time” in following three different ways.
Public static void tellTime(hour, min); // Only hour and minutes
Public static void tellTime(hour, min, sec); // Only hour, minutes and also seconds
Public static void tellTime(date, hour, min, sec); // Date of the month, and all.
Java can do the same thing. If method receives enough information it can do the same task in different ways. This is what you called as overloading and it provides “Polymorphism” features in java.
Sample Program:
Case: We will define three variables and three methods with same name. It’s your computers work to catch the right method according to arguments it receives.
public class MethodOverloading
{
public static void main(String[] args)
{
String aText1 = "Text 1";
String aText2 = "Text 2";
String aText3 = "Text 3";
aMethod(aText1);
aMethod(aText1,aText2);
aMethod(aText1,aText2,aText3);
}
public static void aMethod(String text)
{
System.out.println("I received one text only: " + text);
}
public static void aMethod(String text, String text2)
{
System.out.println("I received two text only: " + text + " and " + text2);
}
public static void aMethod(String text, String text2, String text3)
{
System.out.println("I received all texts: " + text + ", " + text2 + " and " + text3);
}
}
The Output is:
Tip: Be careful, If you have a mixed collection arguments of integer, long like data types, there may be unexpected errors. To avoid such errors, when assigning values use letter ‘L’ for ‘long’ values, and ‘f’ for float values.
Ex: long aLong = 11338833L;
Ex: float aFloat = 34.7f;
How to Overload Constructors?
Constructor methods can receive arguments and be overloaded. If you explicitly create a constructor for a class, the automatically created constructor does not exist.
No comments:
Post a Comment