Java Reference
In-Depth Information
The Wrapper Classes
There are situations in Java programming where you want a primitive data type to take on
the form of java.lang.Object. The developers of Java realized this and created what is
referred to as the wrapper classes. There are eight wrapper classes, one for each of the
eight primitive data types. We use the term wrapper because their main purpose is to wrap
a primitive data type into a Java object.
For example, the java.lang.Integer class is used to wrap an int. The Integer class has two
constructors:
public Integer(int value)
public Integer(String value) throws NumberFormatException
(Note that the String parameter is parsed into an int.) Whichever constructor you use, the
int value is stored as a field in the class and is retrieved using the method:
public int intValue()
Why create an object to store a simple 32-bit int? Because the wrapper class Integer is
just that—a class. It therefore extends Object, and can be used in any situation where an
Object is required.
Wrapper classes are commonly used with the Java Collections Framework, a set of
classes that represent commonly used data structures such as sets, trees, and hash tables.
(Collections are discussed in detail in Chapter 9, “Collections.”) These data structures only
store objects of type Object, which is great when working with Java objects, but unfortunate
when you want to use the data structures for storing primitive data types.
The solution is to wrap each primitive type in its corresponding wrapper class. The wrap-
per classes are found in the java.lang package, and include:
Byte
Short
Integer
Long
Float
Double
Character
Boolean
Each wrapper class has constructors similar to the two in Integer, and each class has
methods for retrieving the primitive type from the wrapper object. View the J2SE docu-
mentation to view the constructors and methods of each class.
Heterogeneous Collections
A common use of polymorphism is to create a collection of data that is not all
the same type, but has a common parent. A collection of different objects is
referred to as a heterogeneous collection .
Search WWH ::




Custom Search