Java Java Objects Meet Objects Methods

Lakindu Jayathilaka
Lakindu Jayathilaka
15,227 Points

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,516 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