Java Reference
In-Depth Information
String getName();
* Return a list of the players that are on this
* team.
List<? extends Player> getPlayerList();
* Add a player to the team.
void addPlayer(Player toAdd);
* Remove a player from the team.
void removePlayer(Player toRemove);
This interface allows us to get the name of the team, assign a player to the team, remove a
player from the team, and get a list of all of the players who are currently on the team. Note
that we are using a parameterized list that allows us to get back not just a Player object but
any object that extends the Player interface; we will talk more about parameterized types in
Chapter 8 .
The reason we are talking about these interfaces is that we now have an object (the Team ob-
ject) that will contain references to Player objects. And because we now have a way to store
references to an object, we also have a way to defeat the garbage collector. All we have to do
to get a memory leak is to forget to remove a Player object from a Team when, say, a play-
er retires (rather than being moved to a different team). We might not use that Player object
anymore, but there will still be a reference to the object that can be traced and that will keep
the garbage collector from reclaiming the space used by the object.
A memory leak in this case is not very likely, but anyone using Java needs to know that any
compilation of references is a potential area for a memory leak. If there are numerous places
where a reference to an object might be stored, we have to make sure that all of those referen-
ces are deleted when we are done with the object. If any one of them remains, the object will
remain, taking up the space that could otherwise be reused. So even though garbage collection
frees us from having to think about when the memory taken up by an object can be reclaimed,
we still need to be careful and make sure that when we are done with an object, we clear the
references in our program to allow the garbage collector to do its work.
Search WWH ::

Custom Search