0

Why do we set this.color = c and then ignore it in the main class?

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()); } }

22nd Apr 2019, 5:08 PM
Mike Smith
Mike Smith - avatar
3 ответов
+ 4
setColor(String c) is a method which expects a String and c is the variable to store this String. in main class: v.setColor("Red") in method: c = "Red" Now you are able to do something with this String --> this.color = c. You could also write String color = "yellow" v1.setColor(color) --> c = "yellow" --> this.color = c
22nd Apr 2019, 7:27 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
You no need to use this keyword here, this keyword is an reference variable that refers to the current object, so you only need to use 'this' if the instance variable and parameters got the same name to distinguish local variable and instance variable
22nd Apr 2019, 6:03 PM
JavaBobbo
JavaBobbo - avatar
+ 1
thanks for the help. it makes more sense now.
23rd Apr 2019, 7:50 AM
Mike Smith
Mike Smith - avatar