+ 1

Why this keyword is used

Even i omitted this keyword in this program the program runs without any error public class Vehicle { private String color; // Getter public String getColor() { return color; } // Setter public void setColor(String c) { this.color = c; } } class Program { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); v1.setColor("Red"); System.out.println(v1.getColor()); } } rate my question if this question is good

16th Jul 2016, 6:18 AM
Sumit kumar
Sumit kumar - avatar
9 Answers
+ 4
this is reference to a current object which u r using this keyword is passed implicitly even if don't mention. one of the use of this keyword is suppose say if fuction parameter is same as class variable they u have to use this keyword public void setColor(String color){ this.color = color; } this use to avoid error
3rd Sep 2016, 6:39 AM
Dinesh C
Dinesh C - avatar
+ 2
this keyword can be used to refer to any member of the current object from within an instance Method or a constructor.
16th Jul 2016, 12:36 PM
Preeti.Bhushania
Preeti.Bhushania - avatar
+ 2
private String a="class variable"; public void doSomething(){ String a = "local variable"; System.out.println (a); System.out.println (this.a); } Try to run this code and see the output. If we don't have "this" keyword, we couldn't print "class variable".
16th Jul 2016, 1:19 PM
WPimpong
WPimpong - avatar
+ 1
What keyword are you talking about
16th Jul 2016, 8:27 AM
Gershon Fosu
Gershon Fosu - avatar
0
"this" keyword
17th Jul 2016, 1:11 AM
WPimpong
WPimpong - avatar
0
we use variable's value in other class for using this keyword it is simple to use like: this.a,this.b
17th Jul 2016, 6:57 AM
shreyash raiyani
shreyash raiyani - avatar
0
this keyword indicates the current object of the class, as you know this never be used with static variable/Attribute because it's memory allocation type is static. n this used only for dynamic type of memory blocks/objects. now at the run time may be there are several objects/instances of current class, to identify and accessing Attributes and methods of the current object, we use 'this' keyword.
24th Jul 2016, 4:27 AM
jayesh malviya
jayesh malviya - avatar
0
this key word is an implicit pointer to the object ur currently using since ur code runs with in a particular object itself it runs without this keyword.
24th Jul 2016, 7:18 PM
Dinesh C
Dinesh C - avatar
0
this is like an object created for that class implicitly.. so using 'this' we can access the attributes and behaviour inside the class
3rd Sep 2016, 4:57 AM
Tom P Samuel
Tom P Samuel - avatar