Java Reference
In-Depth Information
stance, if there are many classes that implement an existing interface, then lots of code
can be broken if that interface were to be changed. This would create a situation where
backward compatibility would not be possible. In such a case, it would make sense to
place a default method implementation into an interface, rather than forcing all classes
to implement a new method that is placed within the interface. This is the reason why
default methods became a necessity, and were included in the Java 8 release.
To create a default method (a.k.a. “defender method”) within an interface, use the
keyword default within the method signature, and include a method implementa-
tion. An interface can contain zero or more default methods. In the solution to this re-
cipe, the listPlayers() method is a default method within the TeamType inter-
face, and any class implementing TeamType will automatically inherit the default im-
plementation. Theoretically, any classes that implement TeamType would be com-
pletely unaffected by the addition of the listPlayers() default method. This en-
ables one to alter an interface without breaking backward compatibility, which can be
of great value.
5-8. Constructing Instances of the Same
Class with Different Values
Problem
Your application requires the ability to construct instances of the same object, but each
object instance needs to contain different values, thereby creating different types of the
same object.
Solution
Make use of the builder pattern in order to build different types of the same object us-
ing a step-by-step procedure. For instance, suppose that you are interested in creating
the different teams for a sports league. Each of the teams must contain the same attrib-
utes, but the values for those attributes vary by team. So you create many objects of the
same type, but each of the objects is unique. The following code demonstrates the
builder pattern, which can be used to create the required teams.
Search WWH ::




Custom Search