Looking For Anything Specific?

ads header

Overloading in JAVA

 OOPS CONCEPT



Overloading 

Two methods are set to be overloaded if and only if both methods having the same name but different argument types. overloading is not there in the C language. In the C language method overloading concept, not available hence we cant declare multiple methods with the same name and different argument types. If there is a change in argument type,    compulsory we should go for a new method name thus it increases the complexity of programming.

In c language
abs(int i)    abs(10)
labs(long i)    labs(10L)
fabs(float i)     fabs(10.5F)


But in java, we can declare multiple methods with same name but different arguments types such types methods are called overloaded methods.
abs(int i)
abs(long l)
abs(float f)

having overloading concept in java reduces the complexity of programming 


class test {

public void m ()
{
System.out.println("no-arg");
}

public void m (int i )
{
System.out.println("int -arg");
}

public void m (double i )
{
System.out.println("double -arg");
}
 
public static void main(String [] args)
{
    test t=new Test();
    t.m();
    t.m(10);
    t.m(10.5);
}

}


Output




CASE  1

 class Main{

public void m(String  s)

{

    System.out.println("String -Version");

}


public void m(Object o)

{

    System.out.println("Object  -Version");

}

public static void main (String [] args)

{

    Main t=new Main();

    t.m(new Object());

    t.m("STR");

    t.m(null);

}


while resolving overloaded methods compiler will always give precedence for child  type argument when compared with the parent type argument







CASE  2

class Main{

public void m(int x )

{

    System.out.println("Genral Method ");

}


public void m(int ... x)

{

    System.out.println("Var-arg Method");

}

public static void main (String [] args)

{

    Main t=new Main();

    t.m();

    t.m(10,20);

    t.m(10);

}







There is one special property of the var-arg method.
In general var -arg method get the least priority,    that is if no other method match then the only var-arg method will get chance.  It exactly the same as the default case inside the switch.





Post a Comment

0 Comments