When should I use “this” in a class?
I know that this
refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x
instead of this.x
in some of the methods? May be x
will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.
What about this.method()
? Can I use it? Should I use it. If I just use method()
, will it not be, by default, applied to the current object?
java oop this
add a comment |
I know that this
refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x
instead of this.x
in some of the methods? May be x
will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.
What about this.method()
? Can I use it? Should I use it. If I just use method()
, will it not be, by default, applied to the current object?
java oop this
add a comment |
I know that this
refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x
instead of this.x
in some of the methods? May be x
will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.
What about this.method()
? Can I use it? Should I use it. If I just use method()
, will it not be, by default, applied to the current object?
java oop this
I know that this
refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x
instead of this.x
in some of the methods? May be x
will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.
What about this.method()
? Can I use it? Should I use it. If I just use method()
, will it not be, by default, applied to the current object?
java oop this
java oop this
edited Apr 27 '10 at 8:37
Gabriel Ščerbák
13.2k63049
13.2k63049
asked Mar 9 '10 at 17:57
RomanRoman
27.1k124276366
27.1k124276366
add a comment |
add a comment |
17 Answers
17
active
oldest
votes
The this
keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. 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.x
. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
private String name;
public void setName(String name)
this.name = name;
Case 2: Using this
as an argument passed to another object.
public class Foo
public String useBarMethod()
Bar theBar = new Bar();
return theBar.barMethod(this);
public String getName()
return "Foo";
public class Bar
public void barMethod(Foo obj)
obj.getName();
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, ...)
to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
public Foo()
this("Some default value for bar");
//optional other lines
public Foo(String bar)
// Do something with bar
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.
14
+1 For mentioning that you can also pass this as an argument. this is not only used for scope disambiguation.
– Alex Jasmin
Mar 9 '10 at 18:24
12
Of course there is alsothis(arg1, arg2, ...)
inside a constructor.
– Thomas Eding
Mar 9 '10 at 18:41
9
@Hazior: I tend to write a short answer and then add to it over time. Sometimes that overlaps with other people's answers, sometimes not. In the case of my latest edit, trinithis pointed out another common use ofthis
that I forgot, so I added it to my answer. I don't see anything wrong with this because the end result is a better answer overall, which is precisely the purpose of SO. I also try to give credit wherever possible, as I did in the case of trinithis.
– William Brendel
Mar 9 '10 at 21:12
4
You have examples for case 1 and 3. Can you please give an example of case 2 where the current class instance is used as an argument for a method of another class?
– dbconfession
Sep 11 '14 at 21:40
3
@AStar In most of the Java codebases I've worked with over the years,this
is only used if disambiguation is truly necessary, like in my setter example above. Coding styles and "best practices" can vary widely depending on who you ask, of course, but in general, I recommend choosing reasonable patterns and sticking to them. Consistency, even just internally within a single codebase, goes a long way towards readability and maintainability.
– William Brendel
Feb 26 '16 at 5:06
|
show 7 more comments
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:
public class Outer
protected int a;
public class Inner
protected int a;
public int foo()
return Outer.this.a;
public Outer getOuter()
return Outer.this;
add a comment |
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 :)
25
+1 intellisense, yay for being lazy :)
– Tanzelax
Mar 9 '10 at 18:47
But then you have to backspace it after you look it up. Programming is tiring!
– LegendLength
Oct 12 '17 at 14:32
add a comment |
The only need to use the this.
qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x
and this.x
.
3
And if you have duplicate names, one of your variables should be renamed as it's almost definitely named improperly. Or at the very least, could be named better.
– CaffGeek
Mar 9 '10 at 18:12
3
@Chad: It's common practice in Java setter methods. However, outside of setter methods, your statements generally holds.
– William Brendel
Mar 9 '10 at 18:14
2
You may want to usethis.x
to make your code read a little bit more clearly also, the maintainability/readability of code is also a factor that you should be considering...
– Bryan Rehbein
Mar 9 '10 at 18:14
1
@Chad: I cannot agree enthusiastically enough. Good Lord, just because "this." allows you to give two different variables the same name, why would you WANT to?
– BlairHippo
Mar 9 '10 at 18:15
2
@Blair: Reading your answer makes it clear that you don't prefer this practice in setter methods, but many people do (I'd include myself in that list). If I have a setter method that takes a value, clearly the value passed in is to be the "new" value, so adding "new" to the variable name seems to add needless redundancy to the public API.
– Adam Robinson
Mar 9 '10 at 18:17
|
show 8 more comments
"this" is also useful when calling one constructor from another:
public class MyClass
public MyClass(String foo)
this(foo, null);
public MyClass(String foo, String bar)
...
add a comment |
this
is useful in the builder pattern.
public class User
private String firstName;
private String surname;
public User(Builder builder)
firstName = builder.firstName;
surname = builder.surname;
public String getFirstName()
return firstName;
public String getSurname()
return surname;
public static class Builder
private String firstName;
private String surname;
public Builder setFirstName(String firstName)
this.firstName = firstName;
return this;
public Builder setSurname(String surname)
this.surname = surname;
return this;
public User build()
return new User(this);
public static void main(String args)
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
1
This was the type of answer I wanted when I searched and ended up here, but you have no explanation of your code, so most people who are asking about "this", won't understand what "return new user(this);" means, as I don't...
– nckbrz
Apr 11 '14 at 21:25
The Builder pattern is used to specify parameters clearly on construction. Instead of having new User(string, string) with no easy way to tell which string was which, you'd have new Builder().setFirstName("Jane").setSurname("Smith").build(). You return this from the Builder.set...() functions so you can chain them.
– ChrisPhoenix
Sep 7 '15 at 23:43
add a comment |
Unless you have overlapping variable names, its really just for clarity when you're reading the code.
3
Or clutter.....
– Steve Kuo
Mar 10 '10 at 1:03
1
When you see constantly thethis
keyword when it's not necessary it's just boilerplate code making the code harder to read.
– AxeEffect
Oct 8 '13 at 0:21
I just came across an open source project that is demanding all members be prefixed with 'this'. Apart from that the project is very well written but i'm tempted to get into religious debate with them.
– LegendLength
Oct 12 '17 at 14:41
1
@AxeEffect I know this is really old but...this
does NOT make the code harder to read lmao.
– Xatenev
Nov 14 '17 at 14:45
add a comment |
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.g. notepad etc), using this
will make it a whole lot clearer to read.
Imagine this:
public class Hello
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere()
// ....
// More codes
public class World
private String bar;
// Another 10k lines of codes
public void doSomething()
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
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. Lastly, after you have forgotten what s
is, that bar = s
is going to give you the final blow.
Compare it to this:
public void doSomething()
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
- You know
foo
is a variable declared in outer classHello
. - You know
getStringFromSomewhere()
is a method declared in outer class as well. - You know that
bar
belongs toWorld
class, ands
is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
great answer @Jai
– gaurav
May 22 '18 at 10:18
The first reason to shoot would be writing classes with several 10k lines of code especially if the code is already splitted to different classes which don't need to be nested :)
– LuCio
Oct 10 '18 at 11:00
@LuCio Lol true xD
– Jai
Oct 11 '18 at 1:21
add a comment |
@William Brendel answer provided three different use cases in nice way.
Use case 1:
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.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this
can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this)
// Do some thing.
Use case 3:
Implementation of Builder pattern depends on use of this
to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)
add a comment |
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.
private int x;
public void setX(int x)
this.x=x;
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX)
x=newX;
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? Sure. 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.
3
It's not a convention, it's a program language scoping mechanism. What you listed--using newX (I prefer pX for parameter x) is a convention.
– Bill K
Mar 9 '10 at 18:13
@Bill K: I don't understand the distinction you're making. I can choose to name the input variable x, or newX, or pX, or mangroveThroatWarblerX. How is choosing to give it a name identical to the variable it's setting NOT a convention, while prepending "new" or "p" or "Gratuitous Monty Python References" ARE conventions?
– BlairHippo
Mar 9 '10 at 18:20
3
"Gratuitoud Monty Python References" is not a convention, it's the LAW.
– Adam Robinson
Mar 9 '10 at 18:23
+1: We use a different naming standard for arguments and method variables than that for class variables for this reason. We abbreviate arguments/method vars and use full words for class/instance variables.
– Lawrence Dol
Mar 9 '10 at 19:23
Solving it by using a naming convention is, hmm, a convention. Solving it by using a language feature--I guess choosing to never use that language feature or always use it would be a convention... Using this. for every time you access a member would be a convention. Guess it doesn't matter much, I hate .this as well.
– Bill K
Mar 10 '10 at 1:44
add a comment |
Following are the ways to use ‘this’ keyword in java :
- Using
this
keyword to refer current class instance variables - Using
this()
to invoke current class constructor - Using
this
keyword to return the current class instance - Using
this
keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
add a comment |
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
add a comment |
this
is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle
int x;
circle(int x)
this.x =x;
//class variable =local variable
this
can also be use to call one constructor from another constructor. e.g.:
public class circle
int x;
circle()
this(1);
circle(int x)
this.x = x;
add a comment |
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A
private int i;
public A(int i)
this.i = i; // this.i can be used to disambiguate the i being referred to
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method()
clarifies that the call is made by this object.
add a comment |
this
does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. 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.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO
protected int i;
public void modify()
i = 9;
public void thisModify()
this.i = 9;
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m()
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
add a comment |
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window
private Window parent;
public Window (Window parent)
this.parent = parent;
public void addSubWindow()
Window child = new Window(this);
list.add(child);
public void printInfo()
if (parent == null)
System.out.println("root");
else
System.out.println("child");
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.
add a comment |
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.
This really isn't the case. I'm not even sure what case you're thinking of, but an example might be helpful to understand what you're trying to say.
– David Berger
Mar 11 '10 at 23:54
1
Yes. I know what you are explaining involves thread safety. There is no correct answer to this question that involves thread safety. If "this" is necessary to refer to the correct object, then once it does so, the method or attribute will be thread safe if and only if it is synchronized. If the reference is at all ambiguous, it will be ambiguous whether or not multi-threading is an issue.
– David Berger
May 9 '12 at 23:30
add a comment |
protected by Community♦ Jul 31 '15 at 16:12
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
17 Answers
17
active
oldest
votes
17 Answers
17
active
oldest
votes
active
oldest
votes
active
oldest
votes
The this
keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. 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.x
. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
private String name;
public void setName(String name)
this.name = name;
Case 2: Using this
as an argument passed to another object.
public class Foo
public String useBarMethod()
Bar theBar = new Bar();
return theBar.barMethod(this);
public String getName()
return "Foo";
public class Bar
public void barMethod(Foo obj)
obj.getName();
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, ...)
to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
public Foo()
this("Some default value for bar");
//optional other lines
public Foo(String bar)
// Do something with bar
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.
14
+1 For mentioning that you can also pass this as an argument. this is not only used for scope disambiguation.
– Alex Jasmin
Mar 9 '10 at 18:24
12
Of course there is alsothis(arg1, arg2, ...)
inside a constructor.
– Thomas Eding
Mar 9 '10 at 18:41
9
@Hazior: I tend to write a short answer and then add to it over time. Sometimes that overlaps with other people's answers, sometimes not. In the case of my latest edit, trinithis pointed out another common use ofthis
that I forgot, so I added it to my answer. I don't see anything wrong with this because the end result is a better answer overall, which is precisely the purpose of SO. I also try to give credit wherever possible, as I did in the case of trinithis.
– William Brendel
Mar 9 '10 at 21:12
4
You have examples for case 1 and 3. Can you please give an example of case 2 where the current class instance is used as an argument for a method of another class?
– dbconfession
Sep 11 '14 at 21:40
3
@AStar In most of the Java codebases I've worked with over the years,this
is only used if disambiguation is truly necessary, like in my setter example above. Coding styles and "best practices" can vary widely depending on who you ask, of course, but in general, I recommend choosing reasonable patterns and sticking to them. Consistency, even just internally within a single codebase, goes a long way towards readability and maintainability.
– William Brendel
Feb 26 '16 at 5:06
|
show 7 more comments
The this
keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. 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.x
. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
private String name;
public void setName(String name)
this.name = name;
Case 2: Using this
as an argument passed to another object.
public class Foo
public String useBarMethod()
Bar theBar = new Bar();
return theBar.barMethod(this);
public String getName()
return "Foo";
public class Bar
public void barMethod(Foo obj)
obj.getName();
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, ...)
to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
public Foo()
this("Some default value for bar");
//optional other lines
public Foo(String bar)
// Do something with bar
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.
14
+1 For mentioning that you can also pass this as an argument. this is not only used for scope disambiguation.
– Alex Jasmin
Mar 9 '10 at 18:24
12
Of course there is alsothis(arg1, arg2, ...)
inside a constructor.
– Thomas Eding
Mar 9 '10 at 18:41
9
@Hazior: I tend to write a short answer and then add to it over time. Sometimes that overlaps with other people's answers, sometimes not. In the case of my latest edit, trinithis pointed out another common use ofthis
that I forgot, so I added it to my answer. I don't see anything wrong with this because the end result is a better answer overall, which is precisely the purpose of SO. I also try to give credit wherever possible, as I did in the case of trinithis.
– William Brendel
Mar 9 '10 at 21:12
4
You have examples for case 1 and 3. Can you please give an example of case 2 where the current class instance is used as an argument for a method of another class?
– dbconfession
Sep 11 '14 at 21:40
3
@AStar In most of the Java codebases I've worked with over the years,this
is only used if disambiguation is truly necessary, like in my setter example above. Coding styles and "best practices" can vary widely depending on who you ask, of course, but in general, I recommend choosing reasonable patterns and sticking to them. Consistency, even just internally within a single codebase, goes a long way towards readability and maintainability.
– William Brendel
Feb 26 '16 at 5:06
|
show 7 more comments
The this
keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. 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.x
. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
private String name;
public void setName(String name)
this.name = name;
Case 2: Using this
as an argument passed to another object.
public class Foo
public String useBarMethod()
Bar theBar = new Bar();
return theBar.barMethod(this);
public String getName()
return "Foo";
public class Bar
public void barMethod(Foo obj)
obj.getName();
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, ...)
to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
public Foo()
this("Some default value for bar");
//optional other lines
public Foo(String bar)
// Do something with bar
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 this
keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. 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.x
. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
private String name;
public void setName(String name)
this.name = name;
Case 2: Using this
as an argument passed to another object.
public class Foo
public String useBarMethod()
Bar theBar = new Bar();
return theBar.barMethod(this);
public String getName()
return "Foo";
public class Bar
public void barMethod(Foo obj)
obj.getName();
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, ...)
to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
public Foo()
this("Some default value for bar");
//optional other lines
public Foo(String bar)
// Do something with bar
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.
edited Jun 1 '17 at 18:51
Michael
18.5k73368
18.5k73368
answered Mar 9 '10 at 17:59
William BrendelWilliam Brendel
26.3k146677
26.3k146677
14
+1 For mentioning that you can also pass this as an argument. this is not only used for scope disambiguation.
– Alex Jasmin
Mar 9 '10 at 18:24
12
Of course there is alsothis(arg1, arg2, ...)
inside a constructor.
– Thomas Eding
Mar 9 '10 at 18:41
9
@Hazior: I tend to write a short answer and then add to it over time. Sometimes that overlaps with other people's answers, sometimes not. In the case of my latest edit, trinithis pointed out another common use ofthis
that I forgot, so I added it to my answer. I don't see anything wrong with this because the end result is a better answer overall, which is precisely the purpose of SO. I also try to give credit wherever possible, as I did in the case of trinithis.
– William Brendel
Mar 9 '10 at 21:12
4
You have examples for case 1 and 3. Can you please give an example of case 2 where the current class instance is used as an argument for a method of another class?
– dbconfession
Sep 11 '14 at 21:40
3
@AStar In most of the Java codebases I've worked with over the years,this
is only used if disambiguation is truly necessary, like in my setter example above. Coding styles and "best practices" can vary widely depending on who you ask, of course, but in general, I recommend choosing reasonable patterns and sticking to them. Consistency, even just internally within a single codebase, goes a long way towards readability and maintainability.
– William Brendel
Feb 26 '16 at 5:06
|
show 7 more comments
14
+1 For mentioning that you can also pass this as an argument. this is not only used for scope disambiguation.
– Alex Jasmin
Mar 9 '10 at 18:24
12
Of course there is alsothis(arg1, arg2, ...)
inside a constructor.
– Thomas Eding
Mar 9 '10 at 18:41
9
@Hazior: I tend to write a short answer and then add to it over time. Sometimes that overlaps with other people's answers, sometimes not. In the case of my latest edit, trinithis pointed out another common use ofthis
that I forgot, so I added it to my answer. I don't see anything wrong with this because the end result is a better answer overall, which is precisely the purpose of SO. I also try to give credit wherever possible, as I did in the case of trinithis.
– William Brendel
Mar 9 '10 at 21:12
4
You have examples for case 1 and 3. Can you please give an example of case 2 where the current class instance is used as an argument for a method of another class?
– dbconfession
Sep 11 '14 at 21:40
3
@AStar In most of the Java codebases I've worked with over the years,this
is only used if disambiguation is truly necessary, like in my setter example above. Coding styles and "best practices" can vary widely depending on who you ask, of course, but in general, I recommend choosing reasonable patterns and sticking to them. Consistency, even just internally within a single codebase, goes a long way towards readability and maintainability.
– William Brendel
Feb 26 '16 at 5:06
14
14
+1 For mentioning that you can also pass this as an argument. this is not only used for scope disambiguation.
– Alex Jasmin
Mar 9 '10 at 18:24
+1 For mentioning that you can also pass this as an argument. this is not only used for scope disambiguation.
– Alex Jasmin
Mar 9 '10 at 18:24
12
12
Of course there is also
this(arg1, arg2, ...)
inside a constructor.– Thomas Eding
Mar 9 '10 at 18:41
Of course there is also
this(arg1, arg2, ...)
inside a constructor.– Thomas Eding
Mar 9 '10 at 18:41
9
9
@Hazior: I tend to write a short answer and then add to it over time. Sometimes that overlaps with other people's answers, sometimes not. In the case of my latest edit, trinithis pointed out another common use of
this
that I forgot, so I added it to my answer. I don't see anything wrong with this because the end result is a better answer overall, which is precisely the purpose of SO. I also try to give credit wherever possible, as I did in the case of trinithis.– William Brendel
Mar 9 '10 at 21:12
@Hazior: I tend to write a short answer and then add to it over time. Sometimes that overlaps with other people's answers, sometimes not. In the case of my latest edit, trinithis pointed out another common use of
this
that I forgot, so I added it to my answer. I don't see anything wrong with this because the end result is a better answer overall, which is precisely the purpose of SO. I also try to give credit wherever possible, as I did in the case of trinithis.– William Brendel
Mar 9 '10 at 21:12
4
4
You have examples for case 1 and 3. Can you please give an example of case 2 where the current class instance is used as an argument for a method of another class?
– dbconfession
Sep 11 '14 at 21:40
You have examples for case 1 and 3. Can you please give an example of case 2 where the current class instance is used as an argument for a method of another class?
– dbconfession
Sep 11 '14 at 21:40
3
3
@AStar In most of the Java codebases I've worked with over the years,
this
is only used if disambiguation is truly necessary, like in my setter example above. Coding styles and "best practices" can vary widely depending on who you ask, of course, but in general, I recommend choosing reasonable patterns and sticking to them. Consistency, even just internally within a single codebase, goes a long way towards readability and maintainability.– William Brendel
Feb 26 '16 at 5:06
@AStar In most of the Java codebases I've worked with over the years,
this
is only used if disambiguation is truly necessary, like in my setter example above. Coding styles and "best practices" can vary widely depending on who you ask, of course, but in general, I recommend choosing reasonable patterns and sticking to them. Consistency, even just internally within a single codebase, goes a long way towards readability and maintainability.– William Brendel
Feb 26 '16 at 5:06
|
show 7 more comments
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:
public class Outer
protected int a;
public class Inner
protected int a;
public int foo()
return Outer.this.a;
public Outer getOuter()
return Outer.this;
add a comment |
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:
public class Outer
protected int a;
public class Inner
protected int a;
public int foo()
return Outer.this.a;
public Outer getOuter()
return Outer.this;
add a comment |
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:
public class Outer
protected int a;
public class Inner
protected int a;
public int foo()
return Outer.this.a;
public Outer getOuter()
return Outer.this;
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:
public class Outer
protected int a;
public class Inner
protected int a;
public int foo()
return Outer.this.a;
public Outer getOuter()
return Outer.this;
answered Mar 9 '10 at 18:50
Christopher OezbekChristopher Oezbek
10.1k23357
10.1k23357
add a comment |
add a comment |
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 :)
25
+1 intellisense, yay for being lazy :)
– Tanzelax
Mar 9 '10 at 18:47
But then you have to backspace it after you look it up. Programming is tiring!
– LegendLength
Oct 12 '17 at 14:32
add a comment |
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 :)
25
+1 intellisense, yay for being lazy :)
– Tanzelax
Mar 9 '10 at 18:47
But then you have to backspace it after you look it up. Programming is tiring!
– LegendLength
Oct 12 '17 at 14:32
add a comment |
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 :)
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 :)
answered Mar 9 '10 at 18:02
froadiefroadie
34.7k59146211
34.7k59146211
25
+1 intellisense, yay for being lazy :)
– Tanzelax
Mar 9 '10 at 18:47
But then you have to backspace it after you look it up. Programming is tiring!
– LegendLength
Oct 12 '17 at 14:32
add a comment |
25
+1 intellisense, yay for being lazy :)
– Tanzelax
Mar 9 '10 at 18:47
But then you have to backspace it after you look it up. Programming is tiring!
– LegendLength
Oct 12 '17 at 14:32
25
25
+1 intellisense, yay for being lazy :)
– Tanzelax
Mar 9 '10 at 18:47
+1 intellisense, yay for being lazy :)
– Tanzelax
Mar 9 '10 at 18:47
But then you have to backspace it after you look it up. Programming is tiring!
– LegendLength
Oct 12 '17 at 14:32
But then you have to backspace it after you look it up. Programming is tiring!
– LegendLength
Oct 12 '17 at 14:32
add a comment |
The only need to use the this.
qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x
and this.x
.
3
And if you have duplicate names, one of your variables should be renamed as it's almost definitely named improperly. Or at the very least, could be named better.
– CaffGeek
Mar 9 '10 at 18:12
3
@Chad: It's common practice in Java setter methods. However, outside of setter methods, your statements generally holds.
– William Brendel
Mar 9 '10 at 18:14
2
You may want to usethis.x
to make your code read a little bit more clearly also, the maintainability/readability of code is also a factor that you should be considering...
– Bryan Rehbein
Mar 9 '10 at 18:14
1
@Chad: I cannot agree enthusiastically enough. Good Lord, just because "this." allows you to give two different variables the same name, why would you WANT to?
– BlairHippo
Mar 9 '10 at 18:15
2
@Blair: Reading your answer makes it clear that you don't prefer this practice in setter methods, but many people do (I'd include myself in that list). If I have a setter method that takes a value, clearly the value passed in is to be the "new" value, so adding "new" to the variable name seems to add needless redundancy to the public API.
– Adam Robinson
Mar 9 '10 at 18:17
|
show 8 more comments
The only need to use the this.
qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x
and this.x
.
3
And if you have duplicate names, one of your variables should be renamed as it's almost definitely named improperly. Or at the very least, could be named better.
– CaffGeek
Mar 9 '10 at 18:12
3
@Chad: It's common practice in Java setter methods. However, outside of setter methods, your statements generally holds.
– William Brendel
Mar 9 '10 at 18:14
2
You may want to usethis.x
to make your code read a little bit more clearly also, the maintainability/readability of code is also a factor that you should be considering...
– Bryan Rehbein
Mar 9 '10 at 18:14
1
@Chad: I cannot agree enthusiastically enough. Good Lord, just because "this." allows you to give two different variables the same name, why would you WANT to?
– BlairHippo
Mar 9 '10 at 18:15
2
@Blair: Reading your answer makes it clear that you don't prefer this practice in setter methods, but many people do (I'd include myself in that list). If I have a setter method that takes a value, clearly the value passed in is to be the "new" value, so adding "new" to the variable name seems to add needless redundancy to the public API.
– Adam Robinson
Mar 9 '10 at 18:17
|
show 8 more comments
The only need to use the this.
qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x
and this.x
.
The only need to use the this.
qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x
and this.x
.
answered Mar 9 '10 at 18:01
Adam RobinsonAdam Robinson
147k27252320
147k27252320
3
And if you have duplicate names, one of your variables should be renamed as it's almost definitely named improperly. Or at the very least, could be named better.
– CaffGeek
Mar 9 '10 at 18:12
3
@Chad: It's common practice in Java setter methods. However, outside of setter methods, your statements generally holds.
– William Brendel
Mar 9 '10 at 18:14
2
You may want to usethis.x
to make your code read a little bit more clearly also, the maintainability/readability of code is also a factor that you should be considering...
– Bryan Rehbein
Mar 9 '10 at 18:14
1
@Chad: I cannot agree enthusiastically enough. Good Lord, just because "this." allows you to give two different variables the same name, why would you WANT to?
– BlairHippo
Mar 9 '10 at 18:15
2
@Blair: Reading your answer makes it clear that you don't prefer this practice in setter methods, but many people do (I'd include myself in that list). If I have a setter method that takes a value, clearly the value passed in is to be the "new" value, so adding "new" to the variable name seems to add needless redundancy to the public API.
– Adam Robinson
Mar 9 '10 at 18:17
|
show 8 more comments
3
And if you have duplicate names, one of your variables should be renamed as it's almost definitely named improperly. Or at the very least, could be named better.
– CaffGeek
Mar 9 '10 at 18:12
3
@Chad: It's common practice in Java setter methods. However, outside of setter methods, your statements generally holds.
– William Brendel
Mar 9 '10 at 18:14
2
You may want to usethis.x
to make your code read a little bit more clearly also, the maintainability/readability of code is also a factor that you should be considering...
– Bryan Rehbein
Mar 9 '10 at 18:14
1
@Chad: I cannot agree enthusiastically enough. Good Lord, just because "this." allows you to give two different variables the same name, why would you WANT to?
– BlairHippo
Mar 9 '10 at 18:15
2
@Blair: Reading your answer makes it clear that you don't prefer this practice in setter methods, but many people do (I'd include myself in that list). If I have a setter method that takes a value, clearly the value passed in is to be the "new" value, so adding "new" to the variable name seems to add needless redundancy to the public API.
– Adam Robinson
Mar 9 '10 at 18:17
3
3
And if you have duplicate names, one of your variables should be renamed as it's almost definitely named improperly. Or at the very least, could be named better.
– CaffGeek
Mar 9 '10 at 18:12
And if you have duplicate names, one of your variables should be renamed as it's almost definitely named improperly. Or at the very least, could be named better.
– CaffGeek
Mar 9 '10 at 18:12
3
3
@Chad: It's common practice in Java setter methods. However, outside of setter methods, your statements generally holds.
– William Brendel
Mar 9 '10 at 18:14
@Chad: It's common practice in Java setter methods. However, outside of setter methods, your statements generally holds.
– William Brendel
Mar 9 '10 at 18:14
2
2
You may want to use
this.x
to make your code read a little bit more clearly also, the maintainability/readability of code is also a factor that you should be considering...– Bryan Rehbein
Mar 9 '10 at 18:14
You may want to use
this.x
to make your code read a little bit more clearly also, the maintainability/readability of code is also a factor that you should be considering...– Bryan Rehbein
Mar 9 '10 at 18:14
1
1
@Chad: I cannot agree enthusiastically enough. Good Lord, just because "this." allows you to give two different variables the same name, why would you WANT to?
– BlairHippo
Mar 9 '10 at 18:15
@Chad: I cannot agree enthusiastically enough. Good Lord, just because "this." allows you to give two different variables the same name, why would you WANT to?
– BlairHippo
Mar 9 '10 at 18:15
2
2
@Blair: Reading your answer makes it clear that you don't prefer this practice in setter methods, but many people do (I'd include myself in that list). If I have a setter method that takes a value, clearly the value passed in is to be the "new" value, so adding "new" to the variable name seems to add needless redundancy to the public API.
– Adam Robinson
Mar 9 '10 at 18:17
@Blair: Reading your answer makes it clear that you don't prefer this practice in setter methods, but many people do (I'd include myself in that list). If I have a setter method that takes a value, clearly the value passed in is to be the "new" value, so adding "new" to the variable name seems to add needless redundancy to the public API.
– Adam Robinson
Mar 9 '10 at 18:17
|
show 8 more comments
"this" is also useful when calling one constructor from another:
public class MyClass
public MyClass(String foo)
this(foo, null);
public MyClass(String foo, String bar)
...
add a comment |
"this" is also useful when calling one constructor from another:
public class MyClass
public MyClass(String foo)
this(foo, null);
public MyClass(String foo, String bar)
...
add a comment |
"this" is also useful when calling one constructor from another:
public class MyClass
public MyClass(String foo)
this(foo, null);
public MyClass(String foo, String bar)
...
"this" is also useful when calling one constructor from another:
public class MyClass
public MyClass(String foo)
this(foo, null);
public MyClass(String foo, String bar)
...
answered Mar 9 '10 at 20:14
BenjaminBenjamin
1513
1513
add a comment |
add a comment |
this
is useful in the builder pattern.
public class User
private String firstName;
private String surname;
public User(Builder builder)
firstName = builder.firstName;
surname = builder.surname;
public String getFirstName()
return firstName;
public String getSurname()
return surname;
public static class Builder
private String firstName;
private String surname;
public Builder setFirstName(String firstName)
this.firstName = firstName;
return this;
public Builder setSurname(String surname)
this.surname = surname;
return this;
public User build()
return new User(this);
public static void main(String args)
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
1
This was the type of answer I wanted when I searched and ended up here, but you have no explanation of your code, so most people who are asking about "this", won't understand what "return new user(this);" means, as I don't...
– nckbrz
Apr 11 '14 at 21:25
The Builder pattern is used to specify parameters clearly on construction. Instead of having new User(string, string) with no easy way to tell which string was which, you'd have new Builder().setFirstName("Jane").setSurname("Smith").build(). You return this from the Builder.set...() functions so you can chain them.
– ChrisPhoenix
Sep 7 '15 at 23:43
add a comment |
this
is useful in the builder pattern.
public class User
private String firstName;
private String surname;
public User(Builder builder)
firstName = builder.firstName;
surname = builder.surname;
public String getFirstName()
return firstName;
public String getSurname()
return surname;
public static class Builder
private String firstName;
private String surname;
public Builder setFirstName(String firstName)
this.firstName = firstName;
return this;
public Builder setSurname(String surname)
this.surname = surname;
return this;
public User build()
return new User(this);
public static void main(String args)
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
1
This was the type of answer I wanted when I searched and ended up here, but you have no explanation of your code, so most people who are asking about "this", won't understand what "return new user(this);" means, as I don't...
– nckbrz
Apr 11 '14 at 21:25
The Builder pattern is used to specify parameters clearly on construction. Instead of having new User(string, string) with no easy way to tell which string was which, you'd have new Builder().setFirstName("Jane").setSurname("Smith").build(). You return this from the Builder.set...() functions so you can chain them.
– ChrisPhoenix
Sep 7 '15 at 23:43
add a comment |
this
is useful in the builder pattern.
public class User
private String firstName;
private String surname;
public User(Builder builder)
firstName = builder.firstName;
surname = builder.surname;
public String getFirstName()
return firstName;
public String getSurname()
return surname;
public static class Builder
private String firstName;
private String surname;
public Builder setFirstName(String firstName)
this.firstName = firstName;
return this;
public Builder setSurname(String surname)
this.surname = surname;
return this;
public User build()
return new User(this);
public static void main(String args)
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
this
is useful in the builder pattern.
public class User
private String firstName;
private String surname;
public User(Builder builder)
firstName = builder.firstName;
surname = builder.surname;
public String getFirstName()
return firstName;
public String getSurname()
return surname;
public static class Builder
private String firstName;
private String surname;
public Builder setFirstName(String firstName)
this.firstName = firstName;
return this;
public Builder setSurname(String surname)
this.surname = surname;
return this;
public User build()
return new User(this);
public static void main(String args)
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
edited Nov 18 '17 at 13:00
andrzej.szmukala
374311
374311
answered Jul 28 '11 at 12:16
Kieren DixonKieren Dixon
86889
86889
1
This was the type of answer I wanted when I searched and ended up here, but you have no explanation of your code, so most people who are asking about "this", won't understand what "return new user(this);" means, as I don't...
– nckbrz
Apr 11 '14 at 21:25
The Builder pattern is used to specify parameters clearly on construction. Instead of having new User(string, string) with no easy way to tell which string was which, you'd have new Builder().setFirstName("Jane").setSurname("Smith").build(). You return this from the Builder.set...() functions so you can chain them.
– ChrisPhoenix
Sep 7 '15 at 23:43
add a comment |
1
This was the type of answer I wanted when I searched and ended up here, but you have no explanation of your code, so most people who are asking about "this", won't understand what "return new user(this);" means, as I don't...
– nckbrz
Apr 11 '14 at 21:25
The Builder pattern is used to specify parameters clearly on construction. Instead of having new User(string, string) with no easy way to tell which string was which, you'd have new Builder().setFirstName("Jane").setSurname("Smith").build(). You return this from the Builder.set...() functions so you can chain them.
– ChrisPhoenix
Sep 7 '15 at 23:43
1
1
This was the type of answer I wanted when I searched and ended up here, but you have no explanation of your code, so most people who are asking about "this", won't understand what "return new user(this);" means, as I don't...
– nckbrz
Apr 11 '14 at 21:25
This was the type of answer I wanted when I searched and ended up here, but you have no explanation of your code, so most people who are asking about "this", won't understand what "return new user(this);" means, as I don't...
– nckbrz
Apr 11 '14 at 21:25
The Builder pattern is used to specify parameters clearly on construction. Instead of having new User(string, string) with no easy way to tell which string was which, you'd have new Builder().setFirstName("Jane").setSurname("Smith").build(). You return this from the Builder.set...() functions so you can chain them.
– ChrisPhoenix
Sep 7 '15 at 23:43
The Builder pattern is used to specify parameters clearly on construction. Instead of having new User(string, string) with no easy way to tell which string was which, you'd have new Builder().setFirstName("Jane").setSurname("Smith").build(). You return this from the Builder.set...() functions so you can chain them.
– ChrisPhoenix
Sep 7 '15 at 23:43
add a comment |
Unless you have overlapping variable names, its really just for clarity when you're reading the code.
3
Or clutter.....
– Steve Kuo
Mar 10 '10 at 1:03
1
When you see constantly thethis
keyword when it's not necessary it's just boilerplate code making the code harder to read.
– AxeEffect
Oct 8 '13 at 0:21
I just came across an open source project that is demanding all members be prefixed with 'this'. Apart from that the project is very well written but i'm tempted to get into religious debate with them.
– LegendLength
Oct 12 '17 at 14:41
1
@AxeEffect I know this is really old but...this
does NOT make the code harder to read lmao.
– Xatenev
Nov 14 '17 at 14:45
add a comment |
Unless you have overlapping variable names, its really just for clarity when you're reading the code.
3
Or clutter.....
– Steve Kuo
Mar 10 '10 at 1:03
1
When you see constantly thethis
keyword when it's not necessary it's just boilerplate code making the code harder to read.
– AxeEffect
Oct 8 '13 at 0:21
I just came across an open source project that is demanding all members be prefixed with 'this'. Apart from that the project is very well written but i'm tempted to get into religious debate with them.
– LegendLength
Oct 12 '17 at 14:41
1
@AxeEffect I know this is really old but...this
does NOT make the code harder to read lmao.
– Xatenev
Nov 14 '17 at 14:45
add a comment |
Unless you have overlapping variable names, its really just for clarity when you're reading the code.
Unless you have overlapping variable names, its really just for clarity when you're reading the code.
answered Mar 9 '10 at 18:00
ChickenMilkBombChickenMilkBomb
772517
772517
3
Or clutter.....
– Steve Kuo
Mar 10 '10 at 1:03
1
When you see constantly thethis
keyword when it's not necessary it's just boilerplate code making the code harder to read.
– AxeEffect
Oct 8 '13 at 0:21
I just came across an open source project that is demanding all members be prefixed with 'this'. Apart from that the project is very well written but i'm tempted to get into religious debate with them.
– LegendLength
Oct 12 '17 at 14:41
1
@AxeEffect I know this is really old but...this
does NOT make the code harder to read lmao.
– Xatenev
Nov 14 '17 at 14:45
add a comment |
3
Or clutter.....
– Steve Kuo
Mar 10 '10 at 1:03
1
When you see constantly thethis
keyword when it's not necessary it's just boilerplate code making the code harder to read.
– AxeEffect
Oct 8 '13 at 0:21
I just came across an open source project that is demanding all members be prefixed with 'this'. Apart from that the project is very well written but i'm tempted to get into religious debate with them.
– LegendLength
Oct 12 '17 at 14:41
1
@AxeEffect I know this is really old but...this
does NOT make the code harder to read lmao.
– Xatenev
Nov 14 '17 at 14:45
3
3
Or clutter.....
– Steve Kuo
Mar 10 '10 at 1:03
Or clutter.....
– Steve Kuo
Mar 10 '10 at 1:03
1
1
When you see constantly the
this
keyword when it's not necessary it's just boilerplate code making the code harder to read.– AxeEffect
Oct 8 '13 at 0:21
When you see constantly the
this
keyword when it's not necessary it's just boilerplate code making the code harder to read.– AxeEffect
Oct 8 '13 at 0:21
I just came across an open source project that is demanding all members be prefixed with 'this'. Apart from that the project is very well written but i'm tempted to get into religious debate with them.
– LegendLength
Oct 12 '17 at 14:41
I just came across an open source project that is demanding all members be prefixed with 'this'. Apart from that the project is very well written but i'm tempted to get into religious debate with them.
– LegendLength
Oct 12 '17 at 14:41
1
1
@AxeEffect I know this is really old but...
this
does NOT make the code harder to read lmao.– Xatenev
Nov 14 '17 at 14:45
@AxeEffect I know this is really old but...
this
does NOT make the code harder to read lmao.– Xatenev
Nov 14 '17 at 14:45
add a comment |
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.g. notepad etc), using this
will make it a whole lot clearer to read.
Imagine this:
public class Hello
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere()
// ....
// More codes
public class World
private String bar;
// Another 10k lines of codes
public void doSomething()
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
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. Lastly, after you have forgotten what s
is, that bar = s
is going to give you the final blow.
Compare it to this:
public void doSomething()
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
- You know
foo
is a variable declared in outer classHello
. - You know
getStringFromSomewhere()
is a method declared in outer class as well. - You know that
bar
belongs toWorld
class, ands
is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
great answer @Jai
– gaurav
May 22 '18 at 10:18
The first reason to shoot would be writing classes with several 10k lines of code especially if the code is already splitted to different classes which don't need to be nested :)
– LuCio
Oct 10 '18 at 11:00
@LuCio Lol true xD
– Jai
Oct 11 '18 at 1:21
add a comment |
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.g. notepad etc), using this
will make it a whole lot clearer to read.
Imagine this:
public class Hello
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere()
// ....
// More codes
public class World
private String bar;
// Another 10k lines of codes
public void doSomething()
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
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. Lastly, after you have forgotten what s
is, that bar = s
is going to give you the final blow.
Compare it to this:
public void doSomething()
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
- You know
foo
is a variable declared in outer classHello
. - You know
getStringFromSomewhere()
is a method declared in outer class as well. - You know that
bar
belongs toWorld
class, ands
is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
great answer @Jai
– gaurav
May 22 '18 at 10:18
The first reason to shoot would be writing classes with several 10k lines of code especially if the code is already splitted to different classes which don't need to be nested :)
– LuCio
Oct 10 '18 at 11:00
@LuCio Lol true xD
– Jai
Oct 11 '18 at 1:21
add a comment |
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.g. notepad etc), using this
will make it a whole lot clearer to read.
Imagine this:
public class Hello
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere()
// ....
// More codes
public class World
private String bar;
// Another 10k lines of codes
public void doSomething()
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
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. Lastly, after you have forgotten what s
is, that bar = s
is going to give you the final blow.
Compare it to this:
public void doSomething()
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
- You know
foo
is a variable declared in outer classHello
. - You know
getStringFromSomewhere()
is a method declared in outer class as well. - You know that
bar
belongs toWorld
class, ands
is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do 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.g. notepad etc), using this
will make it a whole lot clearer to read.
Imagine this:
public class Hello
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere()
// ....
// More codes
public class World
private String bar;
// Another 10k lines of codes
public void doSomething()
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
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. Lastly, after you have forgotten what s
is, that bar = s
is going to give you the final blow.
Compare it to this:
public void doSomething()
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
- You know
foo
is a variable declared in outer classHello
. - You know
getStringFromSomewhere()
is a method declared in outer class as well. - You know that
bar
belongs toWorld
class, ands
is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
answered Feb 22 '18 at 1:42
JaiJai
5,73311231
5,73311231
great answer @Jai
– gaurav
May 22 '18 at 10:18
The first reason to shoot would be writing classes with several 10k lines of code especially if the code is already splitted to different classes which don't need to be nested :)
– LuCio
Oct 10 '18 at 11:00
@LuCio Lol true xD
– Jai
Oct 11 '18 at 1:21
add a comment |
great answer @Jai
– gaurav
May 22 '18 at 10:18
The first reason to shoot would be writing classes with several 10k lines of code especially if the code is already splitted to different classes which don't need to be nested :)
– LuCio
Oct 10 '18 at 11:00
@LuCio Lol true xD
– Jai
Oct 11 '18 at 1:21
great answer @Jai
– gaurav
May 22 '18 at 10:18
great answer @Jai
– gaurav
May 22 '18 at 10:18
The first reason to shoot would be writing classes with several 10k lines of code especially if the code is already splitted to different classes which don't need to be nested :)
– LuCio
Oct 10 '18 at 11:00
The first reason to shoot would be writing classes with several 10k lines of code especially if the code is already splitted to different classes which don't need to be nested :)
– LuCio
Oct 10 '18 at 11:00
@LuCio Lol true xD
– Jai
Oct 11 '18 at 1:21
@LuCio Lol true xD
– Jai
Oct 11 '18 at 1:21
add a comment |
@William Brendel answer provided three different use cases in nice way.
Use case 1:
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.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this
can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this)
// Do some thing.
Use case 3:
Implementation of Builder pattern depends on use of this
to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)
add a comment |
@William Brendel answer provided three different use cases in nice way.
Use case 1:
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.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this
can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this)
// Do some thing.
Use case 3:
Implementation of Builder pattern depends on use of this
to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)
add a comment |
@William Brendel answer provided three different use cases in nice way.
Use case 1:
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.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this
can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this)
// Do some thing.
Use case 3:
Implementation of Builder pattern depends on use of this
to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)
@William Brendel answer provided three different use cases in nice way.
Use case 1:
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.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this
can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this)
// Do some thing.
Use case 3:
Implementation of Builder pattern depends on use of this
to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)
edited Sep 25 '17 at 18:31
answered Sep 17 '16 at 16:44
Ravindra babuRavindra babu
29.2k5155134
29.2k5155134
add a comment |
add a comment |
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.
private int x;
public void setX(int x)
this.x=x;
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX)
x=newX;
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? Sure. 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.
3
It's not a convention, it's a program language scoping mechanism. What you listed--using newX (I prefer pX for parameter x) is a convention.
– Bill K
Mar 9 '10 at 18:13
@Bill K: I don't understand the distinction you're making. I can choose to name the input variable x, or newX, or pX, or mangroveThroatWarblerX. How is choosing to give it a name identical to the variable it's setting NOT a convention, while prepending "new" or "p" or "Gratuitous Monty Python References" ARE conventions?
– BlairHippo
Mar 9 '10 at 18:20
3
"Gratuitoud Monty Python References" is not a convention, it's the LAW.
– Adam Robinson
Mar 9 '10 at 18:23
+1: We use a different naming standard for arguments and method variables than that for class variables for this reason. We abbreviate arguments/method vars and use full words for class/instance variables.
– Lawrence Dol
Mar 9 '10 at 19:23
Solving it by using a naming convention is, hmm, a convention. Solving it by using a language feature--I guess choosing to never use that language feature or always use it would be a convention... Using this. for every time you access a member would be a convention. Guess it doesn't matter much, I hate .this as well.
– Bill K
Mar 10 '10 at 1:44
add a comment |
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.
private int x;
public void setX(int x)
this.x=x;
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX)
x=newX;
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? Sure. 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.
3
It's not a convention, it's a program language scoping mechanism. What you listed--using newX (I prefer pX for parameter x) is a convention.
– Bill K
Mar 9 '10 at 18:13
@Bill K: I don't understand the distinction you're making. I can choose to name the input variable x, or newX, or pX, or mangroveThroatWarblerX. How is choosing to give it a name identical to the variable it's setting NOT a convention, while prepending "new" or "p" or "Gratuitous Monty Python References" ARE conventions?
– BlairHippo
Mar 9 '10 at 18:20
3
"Gratuitoud Monty Python References" is not a convention, it's the LAW.
– Adam Robinson
Mar 9 '10 at 18:23
+1: We use a different naming standard for arguments and method variables than that for class variables for this reason. We abbreviate arguments/method vars and use full words for class/instance variables.
– Lawrence Dol
Mar 9 '10 at 19:23
Solving it by using a naming convention is, hmm, a convention. Solving it by using a language feature--I guess choosing to never use that language feature or always use it would be a convention... Using this. for every time you access a member would be a convention. Guess it doesn't matter much, I hate .this as well.
– Bill K
Mar 10 '10 at 1:44
add a comment |
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.
private int x;
public void setX(int x)
this.x=x;
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX)
x=newX;
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? Sure. 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.
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.
private int x;
public void setX(int x)
this.x=x;
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX)
x=newX;
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? Sure. 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.
edited Mar 9 '10 at 18:11
answered Mar 9 '10 at 18:05
BlairHippoBlairHippo
5,90984572
5,90984572
3
It's not a convention, it's a program language scoping mechanism. What you listed--using newX (I prefer pX for parameter x) is a convention.
– Bill K
Mar 9 '10 at 18:13
@Bill K: I don't understand the distinction you're making. I can choose to name the input variable x, or newX, or pX, or mangroveThroatWarblerX. How is choosing to give it a name identical to the variable it's setting NOT a convention, while prepending "new" or "p" or "Gratuitous Monty Python References" ARE conventions?
– BlairHippo
Mar 9 '10 at 18:20
3
"Gratuitoud Monty Python References" is not a convention, it's the LAW.
– Adam Robinson
Mar 9 '10 at 18:23
+1: We use a different naming standard for arguments and method variables than that for class variables for this reason. We abbreviate arguments/method vars and use full words for class/instance variables.
– Lawrence Dol
Mar 9 '10 at 19:23
Solving it by using a naming convention is, hmm, a convention. Solving it by using a language feature--I guess choosing to never use that language feature or always use it would be a convention... Using this. for every time you access a member would be a convention. Guess it doesn't matter much, I hate .this as well.
– Bill K
Mar 10 '10 at 1:44
add a comment |
3
It's not a convention, it's a program language scoping mechanism. What you listed--using newX (I prefer pX for parameter x) is a convention.
– Bill K
Mar 9 '10 at 18:13
@Bill K: I don't understand the distinction you're making. I can choose to name the input variable x, or newX, or pX, or mangroveThroatWarblerX. How is choosing to give it a name identical to the variable it's setting NOT a convention, while prepending "new" or "p" or "Gratuitous Monty Python References" ARE conventions?
– BlairHippo
Mar 9 '10 at 18:20
3
"Gratuitoud Monty Python References" is not a convention, it's the LAW.
– Adam Robinson
Mar 9 '10 at 18:23
+1: We use a different naming standard for arguments and method variables than that for class variables for this reason. We abbreviate arguments/method vars and use full words for class/instance variables.
– Lawrence Dol
Mar 9 '10 at 19:23
Solving it by using a naming convention is, hmm, a convention. Solving it by using a language feature--I guess choosing to never use that language feature or always use it would be a convention... Using this. for every time you access a member would be a convention. Guess it doesn't matter much, I hate .this as well.
– Bill K
Mar 10 '10 at 1:44
3
3
It's not a convention, it's a program language scoping mechanism. What you listed--using newX (I prefer pX for parameter x) is a convention.
– Bill K
Mar 9 '10 at 18:13
It's not a convention, it's a program language scoping mechanism. What you listed--using newX (I prefer pX for parameter x) is a convention.
– Bill K
Mar 9 '10 at 18:13
@Bill K: I don't understand the distinction you're making. I can choose to name the input variable x, or newX, or pX, or mangroveThroatWarblerX. How is choosing to give it a name identical to the variable it's setting NOT a convention, while prepending "new" or "p" or "Gratuitous Monty Python References" ARE conventions?
– BlairHippo
Mar 9 '10 at 18:20
@Bill K: I don't understand the distinction you're making. I can choose to name the input variable x, or newX, or pX, or mangroveThroatWarblerX. How is choosing to give it a name identical to the variable it's setting NOT a convention, while prepending "new" or "p" or "Gratuitous Monty Python References" ARE conventions?
– BlairHippo
Mar 9 '10 at 18:20
3
3
"Gratuitoud Monty Python References" is not a convention, it's the LAW.
– Adam Robinson
Mar 9 '10 at 18:23
"Gratuitoud Monty Python References" is not a convention, it's the LAW.
– Adam Robinson
Mar 9 '10 at 18:23
+1: We use a different naming standard for arguments and method variables than that for class variables for this reason. We abbreviate arguments/method vars and use full words for class/instance variables.
– Lawrence Dol
Mar 9 '10 at 19:23
+1: We use a different naming standard for arguments and method variables than that for class variables for this reason. We abbreviate arguments/method vars and use full words for class/instance variables.
– Lawrence Dol
Mar 9 '10 at 19:23
Solving it by using a naming convention is, hmm, a convention. Solving it by using a language feature--I guess choosing to never use that language feature or always use it would be a convention... Using this. for every time you access a member would be a convention. Guess it doesn't matter much, I hate .this as well.
– Bill K
Mar 10 '10 at 1:44
Solving it by using a naming convention is, hmm, a convention. Solving it by using a language feature--I guess choosing to never use that language feature or always use it would be a convention... Using this. for every time you access a member would be a convention. Guess it doesn't matter much, I hate .this as well.
– Bill K
Mar 10 '10 at 1:44
add a comment |
Following are the ways to use ‘this’ keyword in java :
- Using
this
keyword to refer current class instance variables - Using
this()
to invoke current class constructor - Using
this
keyword to return the current class instance - Using
this
keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
add a comment |
Following are the ways to use ‘this’ keyword in java :
- Using
this
keyword to refer current class instance variables - Using
this()
to invoke current class constructor - Using
this
keyword to return the current class instance - Using
this
keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
add a comment |
Following are the ways to use ‘this’ keyword in java :
- Using
this
keyword to refer current class instance variables - Using
this()
to invoke current class constructor - Using
this
keyword to return the current class instance - Using
this
keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
Following are the ways to use ‘this’ keyword in java :
- Using
this
keyword to refer current class instance variables - Using
this()
to invoke current class constructor - Using
this
keyword to return the current class instance - Using
this
keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
answered Oct 10 '16 at 12:39
roottravellerroottraveller
3,88933440
3,88933440
add a comment |
add a comment |
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
add a comment |
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
add a comment |
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
answered Mar 9 '10 at 19:50
girigiri
11.6k56125167
11.6k56125167
add a comment |
add a comment |
this
is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle
int x;
circle(int x)
this.x =x;
//class variable =local variable
this
can also be use to call one constructor from another constructor. e.g.:
public class circle
int x;
circle()
this(1);
circle(int x)
this.x = x;
add a comment |
this
is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle
int x;
circle(int x)
this.x =x;
//class variable =local variable
this
can also be use to call one constructor from another constructor. e.g.:
public class circle
int x;
circle()
this(1);
circle(int x)
this.x = x;
add a comment |
this
is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle
int x;
circle(int x)
this.x =x;
//class variable =local variable
this
can also be use to call one constructor from another constructor. e.g.:
public class circle
int x;
circle()
this(1);
circle(int x)
this.x = x;
this
is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle
int x;
circle(int x)
this.x =x;
//class variable =local variable
this
can also be use to call one constructor from another constructor. e.g.:
public class circle
int x;
circle()
this(1);
circle(int x)
this.x = x;
edited Jun 28 '15 at 14:13
Sven-Michael Stübe
11.2k43179
11.2k43179
answered Jun 28 '15 at 13:37
nouman shahnouman shah
112
112
add a comment |
add a comment |
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A
private int i;
public A(int i)
this.i = i; // this.i can be used to disambiguate the i being referred to
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method()
clarifies that the call is made by this object.
add a comment |
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A
private int i;
public A(int i)
this.i = i; // this.i can be used to disambiguate the i being referred to
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method()
clarifies that the call is made by this object.
add a comment |
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A
private int i;
public A(int i)
this.i = i; // this.i can be used to disambiguate the i being referred to
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method()
clarifies that the call is made by this object.
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A
private int i;
public A(int i)
this.i = i; // this.i can be used to disambiguate the i being referred to
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method()
clarifies that the call is made by this object.
answered Mar 9 '10 at 18:01
amitamit
11.6k2175118
11.6k2175118
add a comment |
add a comment |
this
does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. 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.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO
protected int i;
public void modify()
i = 9;
public void thisModify()
this.i = 9;
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m()
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
add a comment |
this
does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. 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.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO
protected int i;
public void modify()
i = 9;
public void thisModify()
this.i = 9;
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m()
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
add a comment |
this
does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. 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.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO
protected int i;
public void modify()
i = 9;
public void thisModify()
this.i = 9;
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m()
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
this
does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. 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.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO
protected int i;
public void modify()
i = 9;
public void thisModify()
this.i = 9;
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m()
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
edited Mar 9 '10 at 18:27
answered Mar 9 '10 at 18:05
docdoc
4,83833860
4,83833860
add a comment |
add a comment |
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window
private Window parent;
public Window (Window parent)
this.parent = parent;
public void addSubWindow()
Window child = new Window(this);
list.add(child);
public void printInfo()
if (parent == null)
System.out.println("root");
else
System.out.println("child");
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.
add a comment |
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window
private Window parent;
public Window (Window parent)
this.parent = parent;
public void addSubWindow()
Window child = new Window(this);
list.add(child);
public void printInfo()
if (parent == null)
System.out.println("root");
else
System.out.println("child");
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.
add a comment |
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window
private Window parent;
public Window (Window parent)
this.parent = parent;
public void addSubWindow()
Window child = new Window(this);
list.add(child);
public void printInfo()
if (parent == null)
System.out.println("root");
else
System.out.println("child");
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.
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window
private Window parent;
public Window (Window parent)
this.parent = parent;
public void addSubWindow()
Window child = new Window(this);
list.add(child);
public void printInfo()
if (parent == null)
System.out.println("root");
else
System.out.println("child");
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.
answered Dec 5 '17 at 19:41
AlijaAlija
5112
5112
add a comment |
add a comment |
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.
This really isn't the case. I'm not even sure what case you're thinking of, but an example might be helpful to understand what you're trying to say.
– David Berger
Mar 11 '10 at 23:54
1
Yes. I know what you are explaining involves thread safety. There is no correct answer to this question that involves thread safety. If "this" is necessary to refer to the correct object, then once it does so, the method or attribute will be thread safe if and only if it is synchronized. If the reference is at all ambiguous, it will be ambiguous whether or not multi-threading is an issue.
– David Berger
May 9 '12 at 23:30
add a comment |
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.
This really isn't the case. I'm not even sure what case you're thinking of, but an example might be helpful to understand what you're trying to say.
– David Berger
Mar 11 '10 at 23:54
1
Yes. I know what you are explaining involves thread safety. There is no correct answer to this question that involves thread safety. If "this" is necessary to refer to the correct object, then once it does so, the method or attribute will be thread safe if and only if it is synchronized. If the reference is at all ambiguous, it will be ambiguous whether or not multi-threading is an issue.
– David Berger
May 9 '12 at 23:30
add a comment |
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.
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.
answered Mar 9 '10 at 20:40
Myster OctoberMyster October
13
13
This really isn't the case. I'm not even sure what case you're thinking of, but an example might be helpful to understand what you're trying to say.
– David Berger
Mar 11 '10 at 23:54
1
Yes. I know what you are explaining involves thread safety. There is no correct answer to this question that involves thread safety. If "this" is necessary to refer to the correct object, then once it does so, the method or attribute will be thread safe if and only if it is synchronized. If the reference is at all ambiguous, it will be ambiguous whether or not multi-threading is an issue.
– David Berger
May 9 '12 at 23:30
add a comment |
This really isn't the case. I'm not even sure what case you're thinking of, but an example might be helpful to understand what you're trying to say.
– David Berger
Mar 11 '10 at 23:54
1
Yes. I know what you are explaining involves thread safety. There is no correct answer to this question that involves thread safety. If "this" is necessary to refer to the correct object, then once it does so, the method or attribute will be thread safe if and only if it is synchronized. If the reference is at all ambiguous, it will be ambiguous whether or not multi-threading is an issue.
– David Berger
May 9 '12 at 23:30
This really isn't the case. I'm not even sure what case you're thinking of, but an example might be helpful to understand what you're trying to say.
– David Berger
Mar 11 '10 at 23:54
This really isn't the case. I'm not even sure what case you're thinking of, but an example might be helpful to understand what you're trying to say.
– David Berger
Mar 11 '10 at 23:54
1
1
Yes. I know what you are explaining involves thread safety. There is no correct answer to this question that involves thread safety. If "this" is necessary to refer to the correct object, then once it does so, the method or attribute will be thread safe if and only if it is synchronized. If the reference is at all ambiguous, it will be ambiguous whether or not multi-threading is an issue.
– David Berger
May 9 '12 at 23:30
Yes. I know what you are explaining involves thread safety. There is no correct answer to this question that involves thread safety. If "this" is necessary to refer to the correct object, then once it does so, the method or attribute will be thread safe if and only if it is synchronized. If the reference is at all ambiguous, it will be ambiguous whether or not multi-threading is an issue.
– David Berger
May 9 '12 at 23:30
add a comment |
protected by Community♦ Jul 31 '15 at 16:12
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?