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 Methods

Why didn't we use "this->characterName"?

I am a PHP developer. When referring to a field/member variable inside the class, we use $this keyword. So in Java, we don't need that "this" keyword?

1 Answer

Mihai Craciun
Mihai Craciun
13,519 Points

we use "this" keyword when we refer to variables inside to the object and we have another variable with the same name but outside the object like this:

public class Test(){
private String name;  //this is the variable inside the object

public void setName(String name){
    this.name = name; 
}
}

the variable "name" (the locale one) gets the value passed by the setName(String name) method...because the name is the same we have to specify what name is from the object and what one is from the method