Within an instance method or a constructor,
this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
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
Point class was written like thispublic class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
Using this with a Constructor
From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's anotherRectangle class, with a different implementation from the one in the Objects section.public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
If present, the invocation of another constructor must be the first line in the constructor.
Source: ORACLE
No comments:
Post a Comment