What is the this keyword in Java?
this is a reference to the object whose method or constructor is running.
this.name = name;separates a field from a parameter of the same name.this(...)calls another constructor of the same class.return this;allows method chaining.
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
Point move(int dx) {
this.x += dx;
return this;
}
}
public class Main {
public static void main(String[] args) {
Point p = new Point(1, 2).move(5).move(10);
System.out.println(p.x + "," + p.y);
}
}
Output
16,2
See Java static and this.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |