Section 4.1. Wrapper Classes

   

4.1 Wrapper Classes

As we saw in the last chapter, all of the eight primitive types ( int, short, boolean, double , etc.) are not objects. In order to work with primitive data type variables as if they were objects, Java provides a wrapper class that defines certain constants and methods . Generally, a wrapper class provides behavioral features that enhance the usability of another entity that it "wraps," or contains, without modifying the thing it wraps. In the case of Java primitive data type wrappers, the wrapper embeds the primitive data type as a field and provides methods for retrieving the value in different forms and doing comparisons, as well as constants appropriate to each class of primitive type. For example, in the last chapter we used the java.lang.Integer wrapper class for the primitive type int . Further examples follow.

Note

There is one additional wrapper class, called void . It has no constructors and cannot be instantiated . It is used as a placeholder to reference a Class object that represents the Java keyword void , another primitive type. You may be used, by now, to seeing the main method in example programs starting with public static void main The return type is specified as void (meaning that the method does not return a value). That's what is being referred to there. More on main later .


Wrapper classes are needed because the use of primitive types is more limited than what one can do with objects. A primitive cannot be passed by reference, for example. We will see in later sections in this chapter how that will be useful when we start reading arguments passed to programs from the command line. Wrappers simply allow primitive data types to be used as full-fledged objects in the language. They all offer such methods as equals() , which checks if the value of the specified objects are equivalent, and compareTo() , which performs a signed comparison of two objects.

Note

Objects instantiated from the wrapper classes are immutable; that is, once created, they cannot be modified.


The discussion of wrapper classes starts off this chapter as a bridge to discussing strings and arrays.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net