Java Reference
In-Depth Information
this.city = city;
}
}
As you can see, the object in this solution contains three fields, and each of those
fields is declared as private . However, each field has two accessor meth-
ods—getters and setters—that allow the fields to be indirectly accessible.
How It Works
The JavaBean is an object that is used to hold information so that it can be passed
around and used within an application. One of the most important aspects of a
JavaBean is that its fields are declared as private . This prohibits other classes from
accessing the fields directly. Instead, each field should be encapsulated by methods
defined in order to make them accessible to other classes. These methods must adhere
to the following naming conventions:
Methods used for accessing the field data should be named using a pre-
fix of get , followed by the field name.
Methods used for setting the field data should be named using a prefix
of set , followed by the field name.
For instance, in the solution to this recipe, the Team object contains a field with the
name of players. In order to access that field, a method should be declared that is
named getPlayers . That method should return the data that is contained within the
players field. Likewise, to populate the players field, a method should be de-
clared that is named setPlayers . That method should accept an argument that is of
the same type as the players field, and it should set the value of the players field
equal to the argument. This can be seen in the following code:
public List<Player> getPlayers() {
return players;
}
void setPlayers(List<Player> players) {
Search WWH ::




Custom Search