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

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,271 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.