Method Overloading in Java

Method Overloading (Compile time polymorphism )

 If a class contains more than one method with same name but different number of arguments or same number of arguments but different data types those methods are called overloaded methods. 
Method Overloading in java


a. Same method name but different number of arguments.

Public Class Abc

{
 void m1(int a)
{
}
 void m1(int a,int b)
{
}
}

 b. Same method name & same number of arguments but different data types. 


Public Class Abc
{
void m1(int a)
{


void m1(char ch)
{


}

To achieve method overloading concept one java class sufficient. It is possible to overload any number of methods in single java class. 

Example of method overloading-

Same method name but different number of argument .

package javaPackage;

public class Overloading 
       {
void add(int a)
{
       System.out.println(a);
}
void add(int a , int b) 
        {
System.out.println(a+b);
}
public static void main(String[] args) 
       {
Overloading O = new Overloading();
O.add(12);
O.add(12, 21);
}
}
 Output:
12
33

Example of  method overloading 
Same method name & same number of arguments but different data types. 

package javaPackage;

public class Overloading 
{
void add(int a)
{
System.out.println(a);
}
void add(char ch) 
 {
System.out.println(ch);
}
public static void main(String[] args) 
 {
Overloading O = new Overloading();
O.add(12);
O.add('a');
}
 }

Output:
12
a
Example of method overloading


Constructor Overloading in java
If the class contains more than one constructors with same name but different arguments or same number of arguments with different data types those constructors are called overloaded constructors. 

a.Same constructor name but different number of arguments.

Public Class Test 
{
Test(int a){   
}  
Test(int a,int b){ 
  }
}

b. Same constructor  name & same number of arguments but different data types. 

Public class Test {
Test(int a){  
 }
 Test(char ch){   

}

Example of Constructor overloading-


package javaPackage;


public class Polymorphism 

{
void add(int a) 
{
System.out.println(a);

}
Polymorphism(int a)
       {
System.out.println("this constructor overloading=" + a);
}
Polymorphism(int a , int b)
       {
      System.out.println("This is Constructor overloading ="+(a+b));
}
public static void main(String[] args) 
      {
Polymorphism ph = new Polymorphism(12);
ph.add(34);
Polymorphism sf =new Polymorphism(12 , 23);
sf.add(32);
}

}

Output:
this constructor overloading=12
34
This is Constructor overloading =35

32


Point to remember about the method overloading :







Post a Comment

0 Comments