Method Overloading

Method Overloading:

            If the Class have multiple methods by same name with different parameters is called as Method overloading.

Why Method Overloading ?? Advantage ??

Method overloading Increase the Readability of the program.

Two Type of method overloading

  1. By Increasing the number of the arguments
  2. Changing the data types

By Increasing the number of the arguments

Example:

class No_Of_Args
  {
     void method_name(int a, int b)
       {
          System.out.println(+a+""+b);
       }
     void method_name(int a, int b, int c)
       {
          System.out.println(+a""+b+""+c);
        }
public static void main(String args[])
  {
     No_Of_Args obj=new No_Of_Arg();
     obj.method_name(10,20,30);
     obj.method_name(10,20);
   }
}

Output:
10 20
10 20 30

Changing the data types:

Example:

class No_Of_Args
  {
     void method_name(int a, int b)
       {
          System.out.println(+a+""+b);
       }
     void method_name(double a, double b)
       {
          System.out.println(+a""+b+""+c);
        }
public static void main(String args[])
  {
     No_Of_Args obj=new No_Of_Arg();
     obj.method_name(10.5, 10.5);
     obj.method_name(10,20);
   }
}

Output:
21.0
40

Is Method Overloaing is not possible by changing the return type of method?
class Calculation3
   { 
      int sum(int a,int b)
       {
          System.out.println(a+b);
        } 
     double sum(int a,int b)
        {
         System.out.println(a+b);
         } 
     
 public static void main(String args[])
    { 
      Calculation3 obj=new Calculation3(); 
      int result=obj.sum(20,20); //Compile Time Error 
     
     } 
 }  


int result=obj.sum(20,20);  //Here how can java determine which sum() method should be called


Overload main() method ?? Possible ??
class Overloading1
  { 
     public static void main(int a)
       { 
          System.out.println(a); 
       } 
       
  public static void main(String args[])
     { 
      System.out.println("main() method invoked"); 
      main(10); 
      } 
   } 


Output:
main() method invoked
10

No comments:

Post a Comment