Posted on

If two or more method in a class have same name but different parameters, it is known as method overloading. Overloading always occur in the same class.

1. Differing the Number of parameters.
2. Differing the Data type of parameters
3. Differing the Sequence of Data type of parameters.

Differing the Number of parameters.

In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.

class Calci

{

return a+b;

}

{

return a+b+c;

}

public static void main(String[] args){

Calci c=new Calci ( );

}

}

—————————————————————————————————————————————

Output : 22

33

—————————————————————————————————————————————-

Differing the Data type of parameters

In this example, we have created two methods, first add() method performs addition of two int numbers and second add method performs addition of one int and one double numbers.

public class Caci

{

{

return a+b;

}

{

return a+b;

}

public static void main(String[] args){

Calci c=new Calci ( );

}

}

—————————————————————————————————————————————

Output : 22

22.5

—————————————————————————————————————————————-

Differing the Sequence of Data type of parameters

In this example, we have created two methods,having different sequence of datatype of parameters first add() method performs addition of a int number and a double number and second add method performs addition of a int and a double number.

e.g.:

public class Caci

{

{

return a+b;

}

{

return a+b;

}

public static void main(String[] args){

Calci c=new Calci ( );

}

}

—————————————————————————————————————————————

Output : 22.5

22.5

—————————————————————————————————————————————-

• In overloading method resolution is always takes care by compiler on reference type hence overloading is also considered as compile time polymorphism, static polymorphism or early binding.
• In java, method overloading is not possible by changing the return type of the method only because of ambiguity. And we do so then it will throw compile time error saying “Compile Time Error: method XXX is already defined in class X”.