+ 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?

14th Oct 2017, 3:50 AM
Ree
Ree - avatar
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.
14th Oct 2017, 4:19 AM
Rrestoring faith
Rrestoring faith - avatar
+ 10
This refers to the current object. For ex, this.setColor("Red") will set the color of that particular object as red
14th Oct 2017, 3:54 AM
Meharban Singh
Meharban Singh - avatar
+ 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.
11th Dec 2017, 10:11 AM
Prabhat Thakur
Prabhat Thakur - avatar
11th Dec 2017, 10:13 AM
Prabhat Thakur
Prabhat Thakur - avatar