+ 2

What is the point having the setter, setColor()?

Why do we have to write the setter method setColor, when we can just set it in the constructor Vehicle(). Basically: public class Vehicle { private String color; Vehicle() { this.setColor("Red"); } Vehicle(String c) { this.setColor(c); } // Setter public void setColor(String c) { this.color = c; } } --------------------------------------------- (This is without setter) public class Vehicle { private String color; Vehicle() { this.color = "Red"; } Vehicle(String c) { this.color = c; } }

9th Feb 2017, 11:15 PM
Sathvik Kuthuru
Sathvik Kuthuru - avatar
5 ответов
+ 18
You can use "this" keyword only within your class to refer to an object of this class. If you create an object of a car in the main method you won't be able to change color by using "this". Getters and setters are needed to control user's influence on an object. For example: you need a valid value of the color, so you put some conditions in the setter method to avoid accepting the wrong value.
10th Feb 2017, 12:03 AM
Igor Makarsky
Igor Makarsky - avatar
+ 17
But what if you want to change the color? You won't be able to do it without setColor() method. But it also depends on the purpose of your application. If you want to set car's color only when it is created, without giving the user the ability to change it, you can ommit that setter.
9th Feb 2017, 11:36 PM
Igor Makarsky
Igor Makarsky - avatar
+ 16
Yes, you can do this, if you make the field color public.
10th Feb 2017, 10:29 AM
Igor Makarsky
Igor Makarsky - avatar
+ 2
If you wanted to change the color later, can't you just do this.color = "SomeColor"; I guess that also brings me to my next question. what is the point of getters and setters.
9th Feb 2017, 11:39 PM
Sathvik Kuthuru
Sathvik Kuthuru - avatar
+ 2
so basically getters and setters can be used to check conditions when assigning the value of an instance variable. But just to be clear, if we didn't want to check any conditions could I do this: Vehicle car = new Vehicle(); car.color = "Red";
10th Feb 2017, 12:10 AM
Sathvik Kuthuru
Sathvik Kuthuru - avatar