Saturday 2 March 2013

Method Overloading in java


In Java it is possible to define two or more methods within the same class that share the same name as long as these methods have different sets of parameters (Based on the number of parameters, the types of the parameters and the order of the parameters).  Then the methods are said to be overloaded, and the process is referred as Method Overloading.
            When the overload method is called the Java compiler selects the proper method by examine the number, type and order of the arguments in the call.  Method Overloading is commonly used to create several methods with same name that perform fast accessing.
Note: Two methods differ in only by return type will result in a syntax error.

Example1:      

class overload
{
            int square(int x)
            {
            return x*x;
            }
            double square(double x)
            {
            return x*x;
            }
}
class check
{
            public static void main(String[] args)
            {
                        overload r1=new overload();
                        int k=r1.square(3);
                        double p=r1.square(4.0);
                        System.out.println("k value="+k);
                        System.out.println("p value="+p);
            }
}

Example2:

class overload1
{
            int sum(int x)
            {
            return x+x;
            }
            int sum(int x,int y,int z)
            {
            return x+y+z;
            }
}
class check1
{
            public static void main(String[] args)
            {
                        overload1 r1=new overload1();
                        int k=r1.sum(3,5,7);
                        System.out.println("k value="+k);
            }
}

No comments:

Post a Comment