Java when do you use this




















The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor. Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".

Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this arg0, arg1, I have also seen this used to emphasize the fact that an instance variable is being referenced sans the need for disambiguation , but that is a rare case in my opinion.

The second important use of this beside hiding with a local variable as many answers already say is when accessing an outer instance from a nested non-static class:. You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. Setter methods, for example. Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :.

The only need to use the this. Apart from that, there's no difference in behavior between x and this. There are a lot of good answers, but there is another very minor reason to put this everywhere.

If you have tried opening your source codes from a normal text editor e. This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor. You will struggle to find out where foo resides, until you use the editor's "find" function.

Then you will scream at getStringFromSomewhere for the same reason. Of course, whenever you design something, you create rules. Unless you have overlapping variable names, its really just for clarity when you're reading the code. Offical java documentation page on this provides same use-cases. 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. Implementation of Builder pattern depends on use of this to return the modified object. Keeping builder in separate class fluent interface. Google turned up a page on the Sun site that discusses this a bit.

You're right about the variable; this can indeed be used to differentiate a method variable from a class field. However, I really hate that convention.

Giving two different variables literally identical names is a recipe for bugs. Same results, but with no chance of a bug where you accidentally refer to x when you really meant to be referring to x instead. As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it?

Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity unless the code is crammed full of static import statements , I'm not inclined to use it myself. It is used in the constructor to distinguish between the local and the current class variable which have the same name. When you have to use it, depends on context.

For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one. The difference will be if some method declares local variable with the same name. With respect to William Brendel 's posts and dbconfessions question, regarding case 2. Here is an example:. I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.

To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used. If your object is not concerned with thread safety then there is no reason to specify which object member's value is used. Stack Overflow for Teams — Collaborate and share knowledge with a private group.

Create a free Team What is Teams? Collectives on Stack Overflow. W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use , cookie and privacy policy. Copyright by Refsnes Data. Andrea Andrea 5, 4 4 gold badges 29 29 silver badges 36 36 bronze badges.

We use a tool to stadardise that in our company. The tool rerite code with our without this depending on the company policy. So everbody codes how they like and code is formatted the right way at commit time.

I prefix all instance variables with underscore so I can easily tell the difference between local and instance variables without using this. In C StyleCop wants you to put this. I like that, I agree with this rule. I think it is better than naming something with an underscore at the beginning. I would follow the same rule if I were coding in java. Add a comment. Active Oldest Votes. It's really quite redundant. Improve this answer. For example in Eclipse by default fields are blue, while local variables are black.

Joachim Nice point, Eclipse can even color parameters and local variables differently if the user wishes this is not by default however. Though I agree, when coming across other developers' code and while being unfamiliar at first glance I find this.

Just what I wanted to point out. I don't find it makes it harder to read, and in return, the code remains readable in editors that have less sophisticated syntax highlighting that doesn't distinguish between fields and locals.

I've always had the opinion that you should strive for your code to be easily readable in the most basic of text editor, and if it isn't, there should be a good reason for it. Show 2 more comments. SomeGuyOnAComputer 4 4 bronze badges. Takes half a second to write and can save long minutes when having to figure out whether the guy before you really meant to use the pascal-case property instead of camel-case local there when he made that last minute burst of changes 20 revisions ago.

This is a good answer. My practice is to use 'this' when assigning to fields, which means there is no name conflict in setters or constructors. Yes - by some, no - by others. Andrey Taptunov Andrey Taptunov 3 3 silver badges 7 7 bronze badges. It's debatable. Eric-Karl Eric-Karl 1 1 silver badge 4 4 bronze badges. I think you answered your own question with this: It feels more natural to me to write I perform code reviews and make diffs on different versions using a comparator with no syntax highlighting; not typing this.

I get payed by key pressed and adding this.



0コメント

  • 1000 / 1000