using_this_keyword_2.htm
This document has a reference to Java' s site.
Using the this Keyword
  • Using with a field
  • Using with a constructor

Using this with a Constructor
Note the use of "this" key word , this is an explicit way of creating constructotr
 

public class My_Class
 {
private int x, y;
private int width, height;

public My_Class() { this(0, 0, 0, 0); }
public My_Class(int width, int height) {this(0, 0, width, height); }
public My_Class (int x, int y, int width, int height) {
this.x = x; //here note the use of common name declared at class and function level
this.y = y;// this.y My_Class
s to the address of private int y variable
this.width = width;
this.height = height;
}
}
 


Using this with a Field
 

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the My_Class
 class was written like this

public class My_Class
 {
public int x = 0;
public int y = 0;

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

Also,could have been written like this:
public class My_Class
 {
public int x = 0;
public int y = 0;
//constructor
public My_Class(int x, int y) { this.x = x; this.y = y;}

}

Each argument to the second constructor shadows one of the object's fields—inside the constructor x is a local copy of the constructor's first argument. To refer to the My_Class
 field x, the constructor must use this.x.

This class contains a set of constructors. Each constructor initializes some or all of the My_Class
's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
If present, the invocation of another constructor must be the first line in the constructor.