getColor | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

getColor

If you have a car and you set the color to red. Why would you have to use getColor in the system.out.println(car.getColor());. why cant use just say system.out.println(color);

3rd Jan 2017, 10:41 PM
Jackson Simpson
Jackson Simpson - avatar
2 Answers
+ 5
you can access the color instance variable from inside the car class even if it is private, but from outside it should be accessable only from a getter function. this is a design pattern which makes programming cleaner and more predictable. this way the creator of the class can restrict the use of instance variables. like the user can get it but not change it.
3rd Jan 2017, 10:46 PM
DFX
DFX - avatar
+ 1
same question you can ask yourself..why even using setColor when you can simply obj.color=red well that's the point...you use that methods wich are public so you can access your private variable color and change it's value
3rd Jan 2017, 10:52 PM
Leonida17st
Leonida17st - avatar