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

question from a java newbie

Can someone explain to me the use of getter and setter using the code below? (please provide a very simple explanation as im still new to java 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()); } }

17th Oct 2017, 4:02 AM
oyl
3 Answers
+ 1
In this case, it is useless. You use these methods, when you have some special logic. Say, the String for the color should not be empty. You can verify that in the setter.
17th Oct 2017, 4:45 AM
1of3
1of3 - avatar
+ 1
this a common query for a beginner even i used to wonder about it. the main use of getters and setters is to pass your data type through a condition which you can put in your setters. now suppose you don't need to have yellow color you can put the condition in the setters that if (color. equals("yellow")) { // your wish }
17th Oct 2017, 9:31 AM
shobhit
shobhit - avatar
0
Because color is private to the Vehicle class, main can't access it. It can set the color 'Red' using the setter method. The getter method can be used to find out the color. The purpose is to allow data independence. I could store the color in RGB or HSL numbers and main never needs to know.
17th Oct 2017, 4:43 AM
John Wells
John Wells - avatar