private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
In MyEclipse, you can just generate setter and getter by:
choose the parameter defined -> source -> generate getter and setter
The getter and setter methods can help hide internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
In fact:
Your object uses setter to:
- restrict and validate data passed to the setter
- hide its inner data structure (other object are interested by a service not how the service is built, this can also include optimisation)
- preserve its integrity in every state (changing other fields if required)
it will use getter to
- format data in output as desired by the client
- control a sequence of services (for instance it will provide data if and only if a connection has been established)