+ 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()); } }
1 Respuesta
+ 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.