0

What is the purpose of these setters and getters?

public class Vehicle { private String color; Vehicle() { this.setColor("Red"); } Vehicle(String c) { this.setColor(c); } //part 2 of code // Setter public void setColor(String c) { this.color = c; } // Getter public String getColor() { return color; } } Is everything under the part 2 comment not necessary.

1st Oct 2017, 10:26 PM
Karl Kanhai
Karl Kanhai - avatar
1 Antwort
+ 6
As you learn more you'll begin to understand why this can be an important way of encapsulating your code. Utilizing a getter and setter allows you to keep your class level variables/members/properties private so that they cannot be directly accessed which could lead to unexpected results in your program further down the line. Let's say that later on you decided that you never wanted the color to be orange, you could add a check to the setter to see if the color that was passed in to the setter was orange and if so throw an error or change it so that it was a default color etc. The fact that you have already created the setter will allow you to know exactly where to go to change your code instead of needing to later create a getter and setter and add the code and also setting the variable as private at that time. This will reduce the likelihood of introducing new errors and vulnerabilities in your code. Also, if you wanted your variable to be read-only you could omit the setter all together. Or remove the getter and make it write-only.
1st Oct 2017, 10:48 PM
ChaoticDawg
ChaoticDawg - avatar