+ 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()); } }
3 Respuestas
+ 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.
+ 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
}
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.