Getters and seters have taken root as the de facto standard in the Java world for encapsulation: the idea that an object hides its internal implementation from class association. This is a general principle of object-oriented programming.
Consider the following class as an example:
// boilerplate public class A { public String b; }
This is a valid single-field Java class. If another class wants to read the BA property, all it needs is:
A a; String val = ab;
and for recording:
ab = val;
The problem is that A no longer controls writing to the internal state. Suppose we learned that b has a maximum length of 1024 characters. Each instance of the entry on b must now be updated to meet the new requirement. Depending on the size of your code base, this can be very expensive.
As an alternative, suppose we used the getter and setter convention to encapsulate b:
Now it looks like this:
A a; String val = a.getB();
and writes:
a.setB(val);
It will take longer to write in the short term, but changing between plans is much easier to integrate by simply changing the setter.
Encapsulation is so highly regarded that, as many other commentators have pointed out, many Java frameworks expect this.
source share