Java Reference
In-Depth Information
Because the Team class implements the TeamType interface, the methods that are
exposed in the interface can be used:
TeamType team = new Team();
team.setName("Juneau Royals");
team.setCity("Chicago");
System.out.println(team.getFullName());
The resulting output:
Juneau Royals - Chicago
How It Works
Interfaces are useful for many reasons. Two of the most important use cases for inter-
faces are conformity and abstraction. Interfaces define a model, and any class that im-
plements the interface must conform to that model. Therefore, if there is a constant
defined within the interface, it will automatically be available for use in the class. If
there is a method defined within the interface, then the class must implement that meth-
od, unless a default implementation has been defined (see Recipe 5-7). Interfaces
provide a nice way to allow classes to conform to a standard.
Interfaces hide unnecessary information from any class that does not need to see it.
Any method that is defined within the interface is made public and accessible to any
class. As demonstrated in the solution to this recipe, an object was created and declared
to be the type of an interface. The interface in the example, TeamType , only includes
a small subset of methods that are available within the Team object. Therefore, the
only methods that are accessible to any class working against an object that has been
declared to be of TeamType are the ones that are defined within the interface. The
class using this interface type cannot see any of the other methods or constants, nor
does it need to. Interfaces are a great way for hiding logic that does not need to be used
by other classes. Another great side effect: A class that implements an interface can be
changed and recompiled without affecting code that works against the interface.
However, if an interface is changed, there could be an effect on any classes that imple-
ment it. Therefore, if the getFullName() method implementation changes, any
class that is coded against the TeamType interface will not be affected because the in-
terface is unchanged. The implementation will change behind the scenes, and any class
Search WWH ::




Custom Search