phone: 016-6933793
e-mail: darknessofsorrow@hotmail.com

Friday 19 October 2012

Overloading

Overloading is the ability to define more than one method with the same name in a class. The compiler is able  to distinguish between the methods because of their method signatures.

Example :
There are nine different ways the print method of System.out object can used :

print.(Object obj)
print.(String s)
print.(boolean b)
print.(char c)
print.(char[] s)
print.(double d)
print.(float f)
print.(int i)
print.(long l

When we use the print method in our code the compiler will determine which method we want to call by looking at the method signature.
For example :

int number = 9;
System.out.print(number);
String text = "nine";
System.out.print(text);
boolean nein = false;
System.out.print(nein); 

Each time a different print method is being called because the parameter type being passed is different. It's useful because the print method will need to vary it works depending on whether it has to deal with a String or integer or boolean.


Overloading Basics
When we give two or more methods the same name within the same class, we are overloading the method name. To do this, we must ensure that the different method definition have something different about their parameter lists.

Example below contains a very simple example of overloading.
/**
This class illustrates overloading.
*/
public class Overload
{
         public static void main(String [] args)
         {
                 double average1 = Overload.getAverage(40.0, 50.0);
                 double average2 = Overload.getAverage(1.0, 2.0, 3.0);
                 char average3 = Overload.getAverage('a', 'c');

                 System.out.println("average1 = " + average1);
                 System.out.println("average2 = " + average2);
                 System.out.println("average3 = " + average3);
         }
         public static double getAverage(double first, double second)
         {
                return (first + second)/2.0;
          }
         public static double getAverage(double first, double second, double third)
         {
                 return (first + second + third)/3.0;
          }
        public static double getAverage(char first, char second)
        {
                return (char)(((int)first + (int)second)/2);
         }
}


**Sample Screen Output**
     average1 = 45.0
     average2 = 2.0
     average3 = b




0 comments: