Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects Meet Objects Constructors

What does the "this" keyword do to the constructor?

So in my code, my question is that does the "this" keyword directing to the private string or the argument string inside my constructor?

MY CODE: class PezDispenser{ private String characterName ;

public PezDispenser(String characterName){ this.characterName = characterName; }

public String getCharacterName(){ return characterName;

} }

2 Answers

mahamataliyoussouf
mahamataliyoussouf
1,638 Points

Actually the this keyword refers to the current object or variable. In our case it refers to the above variable (private String characterName) rather than one used as parameter in the constructor (public PezDispenser(String characterName){........}).

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,258 Points

the this keyword refers to the object itself, so when you call the constructor and feed it a name, the object you construct will have that name. if you make another object, called with another name, that object will have that name, etc.