What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables?
If getters and setters are ever doing more than just the simple get/set, I can figure this one out very quickly, but I'm not 100% clear on how:
public String foo;
is any worse than:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Whereas the former takes a lot less boilerplate code.
Compiling the list up here at the top of what seemed winners to me, from the viewpoint of a Java web dev:
- When you realize you need to do more than just set and get the value, you don't have to change every file in the codebase.
- You can perform validation here.
- You can change the value being set.
- You can hide the internal representation. getAddress() could actually be getting several fields for you.
- You've insulated your public interface from changes under the sheets.
- Some libraries expect this. Reflection, serialization, mock objects.
- Inheriting this class, you can override default functionality.
- You can have different access levels for getter and setter.
- Lazy loading.
- People can easily tell you didn't use Python.