在实例方法或构造函数中,this是对当前对象的引用,该对象是正在调用其方法或构造函数的对象。
情况一:this与field(字段)
Point 类源代码
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
用this关键字改写后:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
情况二:this与Constructor(构造)
在构造函数中,您还可以使用this关键字来调用同一类中的另一个构造函数。这样做称为显式构造函数调用。
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 1, 1);
}
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;
}
...
}
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/java/javahigh/2401.html