Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Shafeeq Ahmed
6,058 Pointsthis
I was told that in Java we can leave or use the 'this' key word. which represent the current instace of a class. what is the difference between using 'this' key word and not using it
3 Answers
Jeremy Hill
29,567 PointsHere is one example as to why you would want to use it:
'''java
public class SomeClass{
private String variable;
public SomeClass(String variable){ this.variable = variable; }
}
'''
This tells the compiler that you want to store the contents passed in in the instance variable and not trying to make the argument equal itself. There are more examples that could be listed.
Shafeeq Ahmed
6,058 PointsThanks Jeremy
Seth Kroger
56,416 PointsThere's often no difference at all, but sometimes you need to use this to tell the difference between a member and local variable. Let's suppose you have a class that doesn't use the m-prefix convention Treehouse courses use (quite common in the wild). The most natural variable names with often conflict. Using this to tell them apart is a common pattern in Java code.
public class GoKart {
private String color;
public GoKart(String color) { // The parameter, which is essentially a local variable,
// overrides the member of the same name.
this.color = color; // this. is necessary to specify the member over the local.
}