Java Reference
In-Depth Information
this.name = personName;
}
}
In this simple Person class, each Person has a name , which is stored as a String variable. The
constructor has a String parameter that's assigned to the Person is name variable when it is con-
structed. Here, you can read the constructor as “the name variable of this person object being con-
structed should be given the value of the personName String provided as a parameter.”
public void printName(){
System.out.println(this.name);
}
If you add an instance method to print the name of a Person object, you can use the this keyword
to identify which name should be printed: “the value assigned to the name variable of this Person
object whose method is being called.”
These examples should illustrate how the this keyword is used. You might be wondering why you would
use it. After all, you could leave it out of the examples and they would function exactly the same way.
public class Person {
String name;
 
public Person(String personName){
name = personName;
}
 
public void printName(){
System.out.println(name);
}
}
As you can see, the use of the this keyword is optional in this situation. It is recommended that you
use it to be explicit and avoid ambiguity, but you could leave it out without impacting your program.
However, there are cases where you must use the this keyword. This is usually when a local vari-
able and an instance variable have the same name. Consider the following example:
public class Person {
String name;
 
public Person(String name){
name = name;
}
 
public void printName(){
System.out.println(name);
}
}
If you try this in Eclipse, you'll see a warning: The assignment to variable name has no
effect . In this case, because name is a local variable for the constructor method, you will be refer-
ring to this local variable if you refer to name inside the method. Essentially, you are saying the
Search WWH ::




Custom Search