Methods Overloading
In java it is possible to create methods that have the same name but different parameter lists and different definitions. This is called method overloading. Method overloading is used when objects are required to perform similar tasks but using different input parameters. When we call a method in an object, java matches up the method name first and the number and type of parameters to decide which one of the definitions to execute. This process is known as polymorphism.
Program illustrations for methods overloading
Class room
{
Float length;
Float breadth;
Room(float x, float y ) // constructor 1
{
Length = x;
Breadth = y;
}
Room ( float x ) //constructor 2
{
Length = breadth = x ;
}
Intarea()
{
Return(length x breadth);
}
}
In the above example we are overloading the method room(). An object representing a rectangular room well be created as
Room room1 = new room( 25.0,15.0); // using constructor1
If the room is square , we may create the corresponding object as
Room room2 = new room ( 20.0); // using constructor2