Java Reference
In-Depth Information
place where an int is required, the compiler will insert a call to the intValue
method behind the scenes. This is known as auto-unboxing. Similar behavior
occurs for the seven other primitive/wrapper pairs. Figure 4.26 illustrates
the use of autoboxing and unboxing. Note that the entities referenced in the
ArrayList are still Integer objects; int cannot be substituted for Integer in the
ArrayList instantiations.
4.6.4 adapters: changing an interface
The adapter pattern
is used to change
the interface of an
existing class to
conform to another.
The adapter pattern is used to change the interface of an existing class to con-
form to another. Sometimes it is used to provide a simpler interface, either
with fewer methods or easier-to-use methods. Other times it is used simply to
change some method names. In either case, the implementation technique is
similar.
We have already seen one example of an adapter: the bridge classes
InputStreamReader and OutputStreamWriter that convert byte-oriented streams
into character-oriented streams.
As another example, our MemoryCell class in Section 4.6.1 uses read and
write . But what if we wanted the interface to use get and put instead? There
are two reasonable alternatives. One is to cut and paste a completely new
class. The other is to use composition , in which we design a new class that
wraps the behavior of an existing class.
We use this technique to implement the new class, StorageCell , in
Figure 4.27. Its methods are implemented by calls to the wrapped Memory-
Cell . It is tempting to use inheritance instead of composition, but inherit-
ance supplements the interface (i.e., it adds additional methods, but leaves
the originals). If that is the appropriate behavior, then indeed inheritance
may be preferable to composition.
1 import java.util.ArrayList;
2
3 public class BoxingDemo
4 {
5 public static void main( String [ ] args )
6 {
7 ArrayList<Integer> arr = new ArrayList<Integer>( );
8
9 arr.add( 46 );
10 int val = arr.get( 0 );
11 System.out.println( "Position 0: " + val );
12 }
13 }
figure 4.26
Autoboxing and
unboxing
 
Search WWH ::




Custom Search