Method Overloading in Java
https://www.computersprofessor.com/2016/06/method-overloading-in-java.html
In java it is
possible to create methods that
have the same but different
parameter lists and different definitions . This is called method
overloading. Method overloading
in used when objects are
required to perform similar tasks
but using different parameters. When we call a method
in an object java matches up the method name first and then the number and
type of parameters to decide which one of the definition to execute. There process
is known as polymorphism.
method overloading means same name but different signature.
Ex:-
Add
(int, int);
Add (int, float);
Add (float, float);
Add(int, int, float);
Add (int, float, double);
Add(float, double);
To create an over loaded
method all we have to
do is to
provide several different method definitions
in the class, all
with the same
name but with
different parameters lists.
The difference may either be in
the number (or) type of arguments,
i.e each parameters list
should be different. note that the
methods return type doesn’t
play any role in this.
class Room
{
float length;
float breadth;
Room(float x,float
y)
{
{
length =x;
breadth=y;
}
Room (float x)
{
length=breadth=x;
}
int area( )
{
return ( lenth * breadth);
}
}
Here we are
over loading the constrictor method Room( ). An object representing
a rectangular room
will be created as
Room room1 = new room(25.0,16.0); (using
constrictor)
On the other hand
if the room is
square, then we may create the
corresponding object as:
Room room2= new
room(20.5); .