Thursday 18 July 2013

Calling a constructor within a constructor in JAVA

Constructor is basically used to initialize variables, but sometimes we have more than one constructor in our class which is also known as Constructor overloading. The object we create is actually the call to constructor and since the name of constructor is same as the name of class so we often call them the object of class.
Now suppose we have a constructor and we want to call another constructor inside it, then this can be done with the help of this keyword.

class abc{
    int i, j;
    abc(){
        i = 10;
    }
    abc(int j){
        this();
        this.j = j;
        //this(); calling this() here will give us error because 
        //   what if we started using i and it had not been initialised
        // thats why we must call this or super in first line while calling constructors
    }
    public static void main(String[] args){
        abc a = new abc(6);
    }
}

this keyword represents object of its own class. It can be used for two purposes, one is two access class member with in the class itself or in more simple language whenever we have to distinguish between a local variable and a class variable we have to use this keyword, like we did in our example 'this.j = j' it means assign the value of local variable j to the class variable j.
Second use of this keyword is to call a constructor within in a constructor.
Note: if you are calling constructor within a constructor than this must come in your first line.
In the above example we are calling a blank constructor within a parametrized constructor, so here first it will call the blank constructor and initializes variable i and then initializes variable j.
Similarly we can call parametrized construction within blank constructor like, this(5) as the first line, but we cannot do this for both the constructors, it will give you compile time error.

No comments:

Post a Comment