public class Foo {
private String name;
// ...
public void setName(String name) {
// This makes it clear that you are assigning
// the value of the parameter "name" to the
// instance variable "name".
this.name = name;
}
// ...
}
在这里this
关键字充当当前类对象的引用变量。但是,这个对象在哪里创建?关键字this
引用哪个对象?逻辑是什么?
"调用该方法的任何对象"。我们无法判断对象是在何处创建的,因为这可能在其他代码中。
看看这个简单、完整的示例:
class Person {
private final String name;
public Person(String name) {
// this refers to the object being constructed
this.name = name;
}
public void printName() {
// this refers to the object the method was called on
System.out.println("My name is " + this.name);
}
}
public class Test {
public static void main(String[] args) {
Person p1 = new Person("Jon");
Person p2 = new Person("Himanshu");
p1.printName(); // Prints "My name is Jon"
p2.printName(); // Prints "My name is Himanshu"
}
}
我们第一次调用 printName()
,我们在p1
引用的对象上调用它 - 所以这就是this
在方法中引用的对象,它打印名称 Jon。第二次我们调用 printName()
,我们在p2
引用的对象上调用它 - 所以这就是this
在方法中引用的对象,它打印了名称 Himanshu。
(需要注意的是,p1
和 p2
本身不是对象 - 它们是变量,变量的值也不是对象,而是引用。有关该差异的更多详细信息,请参阅此答案。
当我们使用时,"this"指的是自己的类和类的当前实例。
当为Android编程时,看到它与类一起使用非常普遍,而不仅仅是属性。
在 MainActivity 类的方法中:
SlidingMenuAdapter slidingMenuAdapter = new SlidingMenuAdapter(MainActivity.this, listSliding);
或者只是
SlidingMenuAdapter slidingMenuAdapter = new SlidingMenuAdapter(this, listSliding);
this
关键字引用类的当前实例。 使用你的类 Foo是你如何看待它:
// We create an instance of the class here
public Foo myFoo;
在你的课堂上,这是将在高层次上发生的事情。
public void setName(String name) {
// this.name = name;
// will be interpreted as when you call myFoo.setName(name);
// myFoo.name = name
}
如果要了解编译器如何表示对象,则可以使用调试器。