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()); } }
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
+ 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
+ 1
thanks for the help. it makes more sense now.