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

Can someone please explain to me why in the constructor we put this.

In java when we write a constructor we write this. to avoid name collision

Ex: private String answer; public Game(String answer){ this.answer = answer; }

Why do we need to put this. and when do we need it? What it's used for?

1 Answer

Look, you have private variable answer, and now in method you have the same variable as a input, and two variables cant have the same name. So you are telling that your private variable, using a keyword this is equal the variable you passed in constructor. If you dont use this keyword, you would have something like { answer = answer }.