+ 8
this.keyword
public class Vehicle { private String color; Vehicle() { this.setColor("Red"); } Vehicle(String c) { this.setColor(c); } // Setter public void setColor(String c) { this.color = c; } } I don't understand the 'this' keyword here. Can anyone explain?
4 Answers
+ 6
Note that in the example you gave it can omitted.
Here's a case where it cannot be:
class Animal{
static Animal firstAnimal;
Animal(){
if(firstAnimal == null)
firstAnimal = this;
}
public static Animal firstBorn(){
return firstAnimal;
}
}
Although, it could help show that you are referring to instance variables. If a local variable has the same name as the global one.
+ 10
This refers to the current object.
For ex, this.setColor("Red") will set the color of that particular object as red
+ 4
This keyword is used to refer the current object ..when we use the (.) operator on this keyword then we can access the member variables of current object.
This keyword can also be used to call one constructor from another constructor of the same class.