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 explain the use of "this." in constructors ?

I am confused on the use of "this." in constructors for java objects.

Hello Jiten,

"this" means "the object you are currently in".

var theObject () { this.someMethod() //equals to "theObject.someMethod()" }

Hope I helped

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

This is referring to the instance itself. We don't really need to use it ever because of the way we named our member variables with an 'm', but if you need to differentiate between a local variable and a member variable of the same name you could do

public class Example {
     // NOTE: this does not use the m prefix like we talked about
    private String firstName;

    public Example(String firstName) {
         // In order to differentiate we use this
         this.firstName = firstName;
     }
}

Make sense?

Thank you i kinda understand it more. Thank you very much craig.