How this and super used with constructors

How this and super used with constructors

Answer : this is a reference to the current object, Within an instance method or a constructor, the object whose method or constructor is being called. You could refer any member of current object from within an instance method or a constructor by using this. Basic reason for using the this keyword is because field been shadowed by a method or constructor parameter. Please see example below:

package com.javahonk.thistest;

public class ThisTest {

    public int x = 0;
    public int y = 0;

    // constructor
    public ThisTest(int a, int b) {
	x = a;
	y = b;
    }

}

// We can also write like this:

class ThisTest2 {

    public int x = 0;
    public int y = 0;

    // constructor
    public ThisTest2(int a, int b) {
	this.x = a;
	this.y = b;
    }

}

 

Every argument of constructor shadows one of the objects fields and inside constructor x is a local copy of the constructors first argument. If we have to refer to the Point field x, constructor must use this.x

Using this with a Constructor: Within the constructor, you could also use this keyword to call another constructor in same class and it is called an explicit constructor invocation. Please see example below:

package com.javahonk.thistest;

public class ThisTest {

     private int x, y;
     private int num1, num2;

     public ThisTest() {
	this(0, 0, 1, 1);
     }

     public ThisTest(int num1, int num2) {
	this(0, 0, num1, num2);
     }

     public ThisTest(int x, int y, int num1, int num2) {
	 this.x = x;
	 this.y = y;
	 this.num1 = num1;
	 this.num2 = num2;
     }

    //..
}

 

Please refer this link to see how super has been used with constructor

Leave a Reply

Your email address will not be published. Required fields are marked *