How Method Overloading Helping in Java - Part 9

I'm sharing my experience with you as these are the questions which have been asked to me while interviewing on java profile.

Where have u observed method overloading helped us in java? Where have you seen in java default classes using method overloading?

We need method overloading because if we have multiple arguments for add method and we have to create multiple methods in that case we will be confused which method to call to perform specific addition.

Example:


class
 PrintOverloading1
{
    public void show(char c)
    {
         System.out.println(c);
    }
    public void show(char c, int number) 
    {
         System.out.println(c + " "+number);
    }
   public void show(char c, String s
    {
         System.out.println(c + " "+s);
    }

}
class demo1
{
   public static void main(String args[])
   {
       PrintOverloading1 obj new PrintOverloading1();
       obj.show('j');
       obj.show('j',10);
       obj.show('j',”Jigyasu Garg”);
   }
}
Output:

j
10

In the above example we have created multiple methods with show name which is common name used for multiple methods. If method overloading in java was not there then as a programmer u might be have big confusion while calling specific method but thanks to Java.

We have method overloading used by default java classes as well like we have object class where we have wait() method which is best example of method overloading.

void
wait()
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
void
wait(long timeout)
Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
void
wait(long timeout, int nanos)
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.


If you still have any question you can reach me any time through email (jigyasu2010@hotmail.com)


Comments

Popular posts from this blog

Important Java Interview Questions - Part 7

Access Modifiers in java