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
Dustin Mordica
7,871 PointsWhy must you use "this.characterName" in the constructor but do not have to use the "this" keyword in the return method?
In the video lesson on Java Objects we are shown two ways of making our code more understandable.
class PezDispenser{
private String characterName;
public PezDispenser(String characterName){
this.characterName = characterName;
}
public String getCharacterName(){
return characterName;
}
}
and
class PezDispenser{
private String mCharacterName;
public PezDispenser(String characterName){
mCharacterName = characterName;
}
public String getCharacterName(){
return mCharacterName;
}
}
The 'this" keyword is being used within the constructor to specify which "characterName" is being referred to. I assume that the "this" keyword does not need to be used within the get-method because it does not have access to the "characterName" being passed a paramter in the constructor? Therefor the only "characterName" it has access to is the class field "characterName?"
Thanks!
Moderator edited: markdown added to question to properly render the code. Please see the Markdown Cheatsheet link at the bottom of the "Add an Answer" section for tips on how to post code to the Community.
1 Answer
Ken Alger
Treehouse TeacherDustin;
Great question!
I've answered similar questions before on the forum here and here, but not explicitly the same question as yours in terms of the return statement.
You have the correct idea about the getCharacterName method as it will be accessing the characterName variable that is in the memory location referenced from the class.
Hope that helps, but post back if you have further questions.
Happy coding,
Ken