Some advantages of using getters and setters (known as encapsulation or data-hiding ):
(originally answered here )
1. Class fields can be made read-only (providing getter only) or write-only (by providing only setter). This gives the class full control over who gets access to / change their fields.
Example:
class EncapsulationExample { private int readOnly = -1; // this value can only be read, not altered private int writeOnly = 0; // this value can only be changed, not viewed public int getReadOnly() { return readOnly; } public int setWriteOnly(int w) { writeOnly = w; } }
2. Class users do not need to know how the class actually stores data. This means that data is shared and independent of users, which makes it easier to modify and maintain code. This allows maintainers to make frequent changes, such as bug fixes, design and performance improvements, without affecting users.
In addition, encapsulated resources are equally accessible to each user and have identical behavior, not dependent on the user, since this behavior is internally defined in the class.
Example (getting value):
class EncapsulationExample { private int value; public int getValue() { return value;
Now, what if I want to return the value twice? I can just change my getter, and all the code that uses my example does not need to be changed and will get twice as much value:
class EncapsulationExample { private int value; public int getValue() { return value*2;
3. Makes the code cleaner more understandable and understandable.
Here is an example:
No encapsulation:
class Box { int widthS;
With encapsulation:
class Box { private int widthS;
See how much more control you have, what information you get and how much clearer it is in the second example. Keep in mind that this example is trivial and in real classes you will have to deal with a lot of resources that are accessed by many different components. Thus, the encapsulation of resources makes it clearer which of them we are referring to and how (getting or setting).
Here is a good SO thread on this topic.
Here's a good read for encapsulating data.