Monday, February 29, 2016

Java - Method Overloading, simple example.



Method Overloading is concept of having same NAME for different methods
in a class performing different but closely related tasks.

For instance, addition is a task, where we may have different methods
for adding integers, decimal and their combinations.
Similarly we may have display methods separately for numbers and strings.

Now,
Methods have signature that enable compiler to distinguish one from another.
The signature of a method constitutes -
Name, No.of arguments, order of arguments and data type.
Note: Return Type is not part of signature, so change in it do not make it
distinct.
So, when we have SAME name for different  methods present in a same class,
we must make distinction in other elements of the signature.
We can have Different no. of arguments/Order of arguments/Data type.
The point is, each overloaded method must be distinct from one another,
so that compiler can identify them uniquely.



Program :

class DisplayMethods {
    String ps = "\nPrice :"; // string literals to avoid retyping
    String cs = "\nCamera :";
    
    /* 3 Methods having the same name 'Dis' with different no. of parameters */
     void Dis(String type, int price){
       System.out.println(type + " - "+ ps + price);
        
    }
      void Dis(String type, String camera, int price){
             System.out.println(type + " - " + cs + camera + ps + price);
              
    }
       void Dis(String type, String camera, String flash, int price){
           System.out.println(type + " -  " + cs + camera + "\nFlash : " + flash + ps + price);
      
        
    }
}
public class Overloading {

    public static void main(String[] args) {
       
        DisplayMethods dm = new DisplayMethods();// Object & Instant Creation

        dm.Dis("Base Phone", 100);
        dm.Dis("Camera Phone", "5 MP RC" ,500);
        dm.Dis("Camera Phone with Flash", "8 MP RC", "LED Flash", 1000);
    }
    
}

Output :

run:
Base Phone - 
Price :100
Camera Phone - 
Camera :5 MP RC
Price :500
Camera Phone with Flash -  
Camera :8 MP RC
Flash : LED Flash
Price :1000

No comments:

Post a Comment