当前的类对象,'this'关键字也指向哪个?

时间:2016-06-06 06:11:42

标签: java

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关键字引用哪个对象?什么是逻辑?

3 个答案:

答案 0 :(得分:3)

它是“调用方法的任何对象”。我们无法分辨对象的创建位置,因为这可能是在其他代码中。

看看这个简单,完整的例子:

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在方法中引用的对象,并打印出名称乔恩。我们第二次调用printName()时,我们在p2引用的对象上调用它 - 所以 this在方法中引用的对象,并且它印有Himanshu这个名字。

(重要的是要注意p1p2本身不是对象 - 它们是变量,变量的值也不是对象,而是引用。请参阅{{3关于这种差异的更多细节。)

答案 1 :(得分:0)

当我们使用"这个"指的是自己的类和类的当前实例。

当Android编程非常常见时,可以在课程中使用它而不仅仅是属性。

在MainActivity类的方法中:

SlidingMenuAdapter slidingMenuAdapter = new SlidingMenuAdapter(MainActivity.this, listSliding);

或只是

SlidingMenuAdapter slidingMenuAdapter = new SlidingMenuAdapter(this, listSliding);

答案 2 :(得分:0)

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
}

如果您想了解编译器如何表示对象,可以使用调试器。

相关问题