Understanding use of “this” in java

2019-08-06 12:44发布

问题:

I'm trying to understand the this keyword in java. I wanted to rewrite this code by using the this keyword instead. Please let me know if I've done it right. Here's the original code:

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;
    } 
}

And here's the re-written code:

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; 
    }
}

Have I done it correctly?

Thanks,

Kevin

EDIT: Thanks for the responses... one more question: in the constructor of the revised code, which side of the equals sign refers to the class variables? For example, in this.title = title;, does this.title refer to the title variable from the constructor or from the class variable?

Based on the responses below, I think the answer is this.title refers to the class variable title.

回答1:

Yes. The this keyword means "the instance of this class that I'm running inside right now". You usually don't need it for variable or method references, but in this (common) case where the constructor parameters have the same name as the fields they're being saved in, using this distinguishes to the compiler between the fields and the parameters.



回答2:

You've used this correctly.

Now, to understand why this works this way notice that the local variable (constructor parameter) names in your previous version of the constructor are different than your class member names. Hence, this wasn't required since there wasn't any ambiguity.

In the second version, since, their names are the same the constructor parameters over shadow or hide the class member fields within the constructor body. Hence, this which points to the current object instance is required to refer to them explicitly.

Also note that this cannot be used from a static context (block or a static method) for the obvious reason that no current object instance is associated with it. It must be used from inside a constructor, instance block or an instance method.



回答3:

From HERE

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

Lets take an example which illustrates what above statement means. I have added comments at appropriate section of code for your reference.

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
    }
}

Now I would suggest you change setVar method to

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 
        } 

and see how it works now.



回答4:

"this" allows you to easily distinguish between variables of the same name within a class/object.

It appears to me that you have used "this" correctly.

I would, however, caution from using the same variable names for multiple uses. In this situation, it is acceptable; however it would be wise to avoid getting into bad programming habits.



回答5:

Yes you have understood this in java correctly. From Sun's original documentation:

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

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



回答6:

look in your Question there are two big concepts of using this has evolved. In the 1ST and foremost case this is used to refer to the current object which has evolved that constructor means this carry a referenceid of current object.... In the 2nd case this is used primarly to distinguish between the local parameters and instance variables because the name of both variables types are same....and it is a rule in java that local variable overshadow the instance variables(of same name) when used in any local block or method...so here this differentiates between the instance variable(this.title) and local variable(title).. And remember this lets u refer directly to the object you can use it to avoid any name space collisions that may ocuur between instance and local variables...



标签: java this