+ 1

Why use "this"?

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()); } } Here, the output is red, but if i don't use this keyword the output is red only. So, why use this?

15th Nov 2020, 2:19 PM
Santosh Pattnaik
Santosh Pattnaik - avatar
3 Réponses
+ 3
Yes. It works.. But "this" means about current object, there about 'v1'.. Instead try this to see difference : public void setColor(String color) { this.color = color ; } color = c ; In this if you use, 'c' just then 'c' refer to parameter variable which is passed(function variable), and color refer to class variable. But in modified code there if you use color=color; then here both points to same method local variable, not class variable.. So you must use this.color=color; to distinguish class variables with local method variable... Hope it helps....
15th Nov 2020, 2:40 PM
Jayakrishna 🇮🇳
0
Thanks, you mean that it might produce a collision between different class methods and attributes with same names
15th Nov 2020, 2:53 PM
Santosh Pattnaik
Santosh Pattnaik - avatar
0
Not exactly that. You can not call different class methods and attributes with just their names, you call with their objects so there no collision but in same class it differenciates the class attributes which are have global scope with the attributes of method's local attributes, which are local scope..
15th Nov 2020, 8:44 PM
Jayakrishna 🇮🇳