Translate

Showing posts with label OOPS. Show all posts
Showing posts with label OOPS. Show all posts

Sunday, 21 December 2014

Variable Length Arguments in java

Java supports variable length argument of one data type. That is we don't need to define number of arguments when its variable for one type of data-type.

For example:-
class Calculator
{
    public int sum (int... a)
    {
        int total=0;
        for(int i=0; i < a.length; i++)
                    total+= a[i];
        return total;
    }
}

A variable length argument allows us to pass any number of arguments while calling the method.
There can be only one variable length argument in a method and if  present it must be the last parameter.

for example
public void method(String S, float f, int... a)
{
   .......
}

Variable length argument reduces number of method if method overloading is being done on the basis of number of parameters.

Saturday, 20 December 2014

this keyword in java

'this' is a reference variable that refers to the object that has called the member function. 'this' is available in all methods of a class except static methods. It is created implicitly so we don't need to declare it.

class Money
{
     private int rs, paisa;
     public void set (int rs, int paisa)
    {
       this.rs = rs;
       this.paisa = paisa;
    }
}

Now in above example rs and paisa to the left of equal op belongs to class and to the right are arguments passed.

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.

Total Pageviews