Translate

Saturday 20 December 2014

Method Overloading in Java

While defining a method it is compulsory to specify return type, otherwise it would give a compile time error. In java following syntax is followed to define a method.

access_specifier return_type method_name(argument 1, ..., argument n)
{
    .....//main body
}

method_name(argument 1, ..., argument n) is known as signature of method.
We can have as many methods in our class as we want as long as their signature is different. We can have multiple methods with the same name as long as their argument list are different. This is called Method Overloading. Either no of argument must be different or type of argument must be different or order of argument must be different.

For example:-

class Calculator
{
    public int sum(int a, int b)
    {
        return a+b;
    }
    public int sum(int a, int b, int c)
    {
        return a+b+c;
    }
    public float sum(int a, int b)
    {
        return a+b;
    }
}

class Java
{
    public static void main(String Args[])
    {
         Calculator calc = new Calculator();
         int x,y;
         float f1;
         x = calc.sum(3,4);
         System.Out.Println("3+4=" + x);
         y = calc.sum(3,4,5);
         System.Out.Println("3+4+5=" + y);
         f1 = calc.sum(1.2f, 1.4f);
         System.Out.Println("1.2+1.4=" + f1);
    }
}

Method overloading is an example of compile time Polymorphism.

No comments:

Post a Comment

Total Pageviews