Contents
Do you need getters and setters for public variables?
You don’t NEED them, but many say you should use them anyway (or rather, they disdain the use of public variables in the first place). This is the subject of many a holy war. IMO, the blind use of getters-setters (at least in Java) is more often than not (not always!!!)
Does it make sense to write getter and setter methods for a public member variable What about private variables?
private data members are generally considered good because they provide encapsulation. Providing getters and setters for them breaks that encapsulation, but it’s still better than public data members because there’s only once access point to that data.
Are setters and getters public?
Generally, it getter and setters are made public to provide acess to other classes.
When do you use getters and setters in Java?
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively. By convention, getters start with the word “get”
What’s the difference between a getter and a public variable?
As for getters–I still can’t come up with much of a difference between a getter and a public final variable. The problem here is that it’s bad OO in either case. You shouldn’t be asking for a value from an object and operating on it–you should be asking an object to do an operation for you.
Can a getter and setter be public in protected context?
In a protected context, its not terribly different to a public context. Foreign possibly rogue functions want access to the data-structure. So no, if they exist they operate like public getters/setters. if you have to perform sanity check before assigning value to the member like strings or array.
What is a public member variable in Java?
A public member variable is basically global variable with a prefix… Not the answer you’re looking for? Browse other questions tagged java class methods private public or ask your own question.
https://www.youtube.com/watch?v=ReyphyJ7qqc