+ 2

Java classes this.blabla question

during the java tutorial when learning about getters and setters, I found that they use both this.color and just color, I know that in JavaScript this is a huge deal, but I tried this, and they both actually seemed to work (link can be found below), can anyone explain what this is about? https://code.sololearn.com/cF5RInwpj86A/?ref=app

1st Jan 2018, 9:05 PM
wout werkman
wout werkman - avatar
2 Respuestas
+ 18
here , in this code , U r not doing anything with class Vehicle1 and with its object v2 , u r just using object v1 of class vehicle , firstly setting color of v1 to be red & then printed it & then u setted its color to blue & printed it //i removed object v2 & class vehicle1 , then also it will work the same ... u can see the code ::: 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()); v1.setColor("Blue"); System.out.println(v1.getColor()); } } //👉i hv given an explanation about "this" in a post but its lost now , btw u can see this post https://www.sololearn.com/Discuss/876647/?ref=app
1st Jan 2018, 9:39 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 1
"This.Color" is simply a direct reference to the field. It will always return the same field. "Color" However, may also refer to a peramiter or variable named in a more local scope like one defined in a function. In such an instance this.Color refers to the object field while Color refers to the local variable. Class person{ private String name; public person (String name) { this.name = name; //field parameter } }
1st Jan 2018, 11:30 PM
josh mizzi
josh mizzi - avatar