even though "this" keyword is not used for setColor("Red") method why does the output gives "Red"?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

even though "this" keyword is not used for setColor("Red") method why does the output gives "Red"??

public class Vehicle { private String color; Vehicle() { } Vehicle(String c) { this.setColor(c);setColor("Red"); } // Setter public void setColor(String c) { this.color = c; } // Getter public String getColor() { return color; } } public class Program { public static void main(String[] args) { //color will be "Red" Vehicle v1 = new Vehicle(); //color will be "Green" Vehicle v2 = new Vehicle("Green"); System.out.println(v2.getColor()); } }

17th Feb 2020, 5:51 AM
anjan s madhyastha
anjan s madhyastha - avatar
1 Answer
+ 1
Because you are setting value in Constructor using setter method. And You have already used this keyword in setter method. One more thing you are having setColor("Red") after this.setColor(c). So it's overriding. Remove setColor("Red") then it will work according to you.
17th Feb 2020, 7:17 AM
A͢J
A͢J - avatar