理解在java中使用“this”

时间:2013-10-11 19:10:26

标签: java this

我正在尝试理解java中的this关键字。我想使用this关键字重写此代码。如果我做得对,请告诉我。这是原始代码:

public class Book {

    private String title;
    private String author;
    private String publisher;

    public Book(String bookTitle, String authorName, String publisherName){
        title = bookTitle;
        author = authorName;
        publisher = publisherName;
    } 
}

这是重写的代码:

public class Book {

    private String title; 
    private String author; 
    private String publisher; 

    public Book(String title, String author, String publisher){
        this.title = title; 
        this.author = author; 
        this.publisher = publisher; 
    }
}

我做得对吗?

谢谢,

凯文

编辑:感谢您的回复...还有一个问题:在修改后的代码的构造函数中,等号的哪一侧引用类变量?例如,在this.title = title;中,this.title是否引用构造函数中的title变量或类变量?

根据以下回答,我认为答案是this.title是指类变量title

6 个答案:

答案 0 :(得分:2)

是。 this关键字表示“我正在运行的此类的实例”。对于变量或方法引用,通常不需要它,但在这种(常见)情况下,构造函数参数与它们保存的字段具有相同的名称,使用this区分编译器之间的编译器。字段和参数。

答案 1 :(得分:1)

您已正确使用this

现在,要理解为什么this以这种方式工作,请注意先前版本的构造函数中的局部变量(构造函数参数)名称与您的成员名称。因此,由于没有任何歧义,因此不需要this

在第二个版本中,因为它们的名称与阴影上的构造函数参数相同,或隐藏构造函数体内的类成员字段。因此,指向当前对象实例的this需要显式引用它们。

另请注意,静态上下文(静态方法> } 无法 em>)由于显而易见的原因,没有当前的对象实例与之关联。它必须在构造函数实例块实例方法中使用。

答案 2 :(得分:1)

来自HERE

  

使用this关键字的最常见原因是因为某个字段   被方法或构造函数参数遮蔽。

让我们举一个例子来说明上述陈述的含义。我已在相应的代码部分添加了注释,供您参考。

public class ThisKeywordExample {

    private int x;
    private int y;

    public void setVar(int x, int y) {
        x = x;  // Setting private variable x value 
        y = y;  // Setting private variable y value
        System.out.println(x + " " + y); // prints 10 20 
    }

    public static void main(String[] args) {
        ThisKeywordExample obj1 = new ThisKeywordExample();
        obj1.setVar(10, 20);
        System.out.println(obj1.x + " " + obj1.y); //prints 0 0 because the effect is limited to the local copies of x &  y in the setVar method
    }
}

现在我建议您将setVar方法更改为

public void setVar(int x, int y) {
            this.x = x;  // Setting private variable x value 
            this.y = y;  // Setting private variable y value
            System.out.println(x + " " + y); // prints 10 20 
        } 

现在看看它是如何运作的。

答案 3 :(得分:0)

“this”允许您轻松区分类/对象中同名变量。

在我看来,您已正确使用“此”。

但是,我会谨慎地使用相同的变量名进行多次使用。在这种情况下,这是可以接受的;但是,避免陷入糟糕的编程习惯是明智的。

答案 4 :(得分:0)

是的,您已正确理解了java 中的this 。来自Sun的原始文档:

  

在实例方法或构造函数中,这是对它的引用   当前对象 - 其方法或构造函数所在的对象   调用。您可以从内部引用当前对象的任何成员   使用它的实例方法或构造函数。

来源:http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

答案 5 :(得分:0)

在你的问题中查看有两个使用它的大概念已经发展。 在第1和最重要的情况下,这用于指代已经发展的当前对象,构造函数意味着它带有当前对象的referenceid .... 在第二种情况下,这主要用于区分本地参数和实例变量,因为两个变量类型的名称相同....并且java中的一个规则是局部变量覆盖实例变量(同名)时用于任何本地块或方法......所以这里区分实例变量(this.title)和局部变量(标题).. 请记住,这可以直接引用您可以使用它的对象,以避免在实例和局部变量之间发生任何名称空间冲突......