this是保存当前对象的引用ID的变量。那么为什么它不能用作引用变量呢?
Temp t = new Temp(); //Temp be any class
t.show(); //show() be any method in Temp
this.show(); // error
这只会抛出一个错误,如果你所在的类没有一个show()
方法或,如果你试图从一个静态的上下文。
this
保存当前对象的引用ID,因此它取决于您在哪里,而不是您刚刚创建的对象。
当前对象不是您上次引用的对象。以下是this
使用的示例:
public class Temp {
private int x = 3;
public void show() {
this.x = 4;
this.show(); // same as show();
}
}
java中的"this"关键字用于引用代码运行的对象。比较对象本身是非常有用的。例子:
public boolean equals(Object object) {
return object == this;
}
下面是另一段代码来帮助你理解:
public class Test {
public Test() {
}
public static void main(String... args) {
Test test = new Test();//original test object
Test test2 = new Test();
test.equals(test);//returns true
test.equals(test2);//returns false
}
public void equals(Test testParameter) {
// in this particular case "this" refers to the
// original test object (defined in the main method)
// as it is the only object calling this method.
return testParameter == this; // "this" is the object that is calling the method
}
}