In what instances would I need to use the this
keyword? I have used it before when creating class objects, but I found that I don't really need it. The program would behave the same way whether or not it had a this
keyword in front of the variable.
For example, these two versions of the same Circle object I created for demonstration produce the same result when used in the Test class, yet one utilizes the this
keyword on its private variables where as the other does not.
Version without the this
keyword:
public class Circle{
private int radius;
public Circle(){
//default radius setting
radius = 1;
}
public Circle(int r){
radius = r;
}
public int getRadius(){
return radius;
}
public void setRadius(int r){
radius = r;
}
}
Version with the this
keyword:
public class Circle{
private int radius;
public Circle(){
//default radius setting
this.radius = 1;
}
public Circle(int r){
this.radius = r;
}
public int getRadius(){
return this.radius;
}
public void setRadius(int r){
this.radius = r;
}
}
The Test class I used to test both objects is:
public class Test{
public static void main(String[] args){
Circle c = new Circle();
System.out.println(c.getRadius());
c.setRadius(6);
System.out.println(c.getRadius());
}
}
Which produces the following output in for both versions of the class Circle when executed in the console:
$ java Test
1
6