Monday, 30 January 2012

Overloading in Java

Introduction:

•In Java, overloading is one of the way to achieve polymorphism.
•Overloading is also called as compile-time or static polymorphism.
•When two or more methods are declared with the same name but with varying/different types or number of parameters, the methods are said to be “overloaded” and this process is called “method overloading”.
•Method overloading is based on two factors:
1) Different types(date types) of parameters.
2) Different number of parameters.

Example on different types of parameters:
void sum(int a)
{
   System.out.println(“sum is: “+a);
}
void sum(float a)
{
   System.out.println(“sum is: “+a);
}

The above methods are having the same name “sum”, but with different types of parameters. One is int type and other is float.

Example on different number of parameters:
void sum(int a)
{
   System.out.println(“sum is: “+a);
}
void sum(int a, int b)
{
   System.out.println(“sum is: “+(a+b));
}

The above methods are having the same name “sum”, but with different number of parameters. One is having one int type and other is having two int parameters.

Constructor Overloading:
•Since constructors are also special kind of methods, constructors can also be overloaded.
•If two are more constructors are declared with same name, but with different types or number of parameters, then the constructors are said to be “overloaded” and this concept is called “constructor overloading”.

•Let’s see an example on constructor overloading…

class Box
{
   int length, width, height;
   Box()
   {
     length = 10; width = 20; height = 30;
   }
   Box(int l, int w, int h)
   {
     length = l; width = w; height = h;
   }
}

2 comments: