0
why do we need getters and setters?
can't we just NOT use private? we can use public and access those variables from anywhere.... so...where's the point of doing that?
4 Answers
+ 2
Encapsulation. In other words, hiding the implementation of your class, so that you can change it any time without worrying about code using your class.
Also, sometimes you don't not even want to provide a setter, and let only some other methods change the value along with other changes, for coherence of the general state of the object or other reason. You may also not provide a getter, too, because users of your class don't necessarily need to know a particular attribute exists, and only the methods of your class will need it.
+ 1
for simple solutions you dont need to, but as your code gets more and more diverse you will find it easier, especially for checking data integrity.
example you made a program that saves grades based on the users input, you can setGrade(intEntered); and instead of checking all the data for valid ammounts everytime you enter a grade you can have the setGrade method check or valid ranges between 0 and 100 and return an error message or prompt if the data doesnt match.. ect.. does that help?
+ 1
wow!
Brad thanks for your answer!
I think I got it now....
I also read some articles on the internet about encapsulation...
thank you all for your answers...
+ 1
getters() are used to get the values from the class where members of class are private we can't access private members by creating instance.
setters() are used to set the values of the class where members of class are private we can't change private members by creating instance.