The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. The names of variables that are declared within a method are local to the method. You can use a name for a local variable or a parameter in a method that is the same as that of a instance variable. If you find it necessary or convenient to do this, then you must use the name this when you refer to the data member of the class from within the method. The variable name by itself will always refer to the variable that is local to the method, not the instance variable. For example, suppose you wanted to add a method to change the radius of a Sphere object to a new radius value that is passed as an argument. You could code this as:
void changeRadius(double radius) {
// Change the instance variable to the argument value
this.radius = radius;
}
No confusion in the duplication of names exists here. It is clear that you are receiving a radius value as a parameter with the name radius and storing it in the radius variable for the class object.
No comments:
Post a Comment