Creating a getter and setter for a private field help to hide the internal implementation of the class. It means that you can change the internal representation without changing the external interface to other classes.
For example if you have a custom class that implements a data structure similar to a sequence of values. The first implementation can use an array of values.
Adding some new functionalities you can decide to change the internal representation of the values from an array to a List.
Here an example.
Original code using an array:
public class MySequence {
private Object[] values;
public Object[] getValues() {
return values;
}
public void setValues(Object[] values) {
this.values = values;
}
}
Then you think can be a good idea to create a method to add a new value. Here you can change the internal implementation, leaving the same interface to the users of the MySequence class.
public class MySequence {
private List<Object> values;
public void add(Object value) {
values.add(value);
}
public Object[] getValues() {
return values.toArray(new Object[values.size()]);
}
public void setValues(Object[] values) {
this.values = Arrays.asList(values);
}
}