Overloading in java



In java method overloading means creating more than a single method with same name with different signatures.
For instance the + sign is used to add ints as well as
concatenate strings . The plus sign behaves differently
depending on the type of its arguments. Therefore the plus
sign is inherently overloaded.

Methods can be overloaded as well..same method with
different parameters is said to be method overloadingis one of the ways that java.----
we can perform the similar operation in different ways for
different parameters.

Constructors can be overloaded as well...Overloaded
Constructors provide multiple ways to initialize a new object

Method overloadingis one of the ways that java implements polymorphism.

In the example three methods are created with same name. java understands these methods with there signatures. java identifies the methods by comparing their signatures like return types, constructor parameters & access modifier used.



public class democlass { 
public void add(int a , int b){
System.out.println("Result: "+a+b);
}
public void add(String a , String b){
System.out.println("Result: "+a+b);
}

public static void main(String[] args) {
democlass democlass=new democlass();
int a=10; 
int b=20;
String temp1="Java";
String temp2="Source blog";
democlass.add(a, b);
democlass.add(temp1, temp2);

}

}


output

Result: 30
Result: JavaSource blog


LinkWithin

Related Posts Plugin for WordPress, Blogger...