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
Matthew Francis
6,967 PointsNewbie - Why is "this" not used here?
public boolean applyGuess(char letter) {
letter = validateGuess(letter);
// Why is it not this.letter? I thought this is used to distinguished between variable names and it's values?*/
}
public void setName(String name) {
this.name = name ;
// Here, this is used to distinguish between the variable name and the value.*/
}
Matthew Francis
6,967 PointsSame here! I came from javascript and I'm just wondering how "this" interacts in java!
1 Answer
Simon Coates
28,695 Pointsyou can use 'this' if the variable you want to access is on the object, but not for local variables/parameters. the 'name' variable is on the object - having a scope (duration/accessibility) throughout the object. Hence 'this' can be used to differentiate it from a local variable with the same name. eg this.name = name ; The letter variable and the second name variable (the parameter) exist only within the methods that use them - not on the object itself. (unless there are multiple variables with the same name in your current scope, the 'this' keyword is optional - eg, if the parameter was rename newName, then the assignment line could be just name = newName )
'this' is used to differentiate between different types of variable (instance vs param/local). see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html and https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
john larson
16,594 Pointsjohn larson
16,594 PointsI don't have an answer, but I'm following your question cause I'm interested in how it compares to JavaScript