Java Reference
In-Depth Information
The wrapper classes
Wrapper class Integer
A variable of a primitive type, like int , is handled differently from a variable of
a class type. A variable of type int contains a value; a variable of a class type
contains the name of an object of the class, which in turn can contain fields with
values. It would be nice to be able to handle int and class-type variables in the
same way. To make this possible, Java provides a class Integer :
Wrapper class
int is discussed
on lesson page
public class Integer {
private int val;
An object of class Integer contains a single instance variable val of type int .
Integer is called a wrapper class since an instance of it wraps an int variable.
Wrapped variable val is private, so it cannot be referenced outside the class.
In fact, we do not even know what name the variable has because the specifica-
tion of class Integer does not say. We used the name val just to be able to write
a declaration. There is no need to know the name because the value of this field
can be accessed only using getter method intValue :
/** = the value of the wrapped int */
public int intValue()
Moreover, there is no setter method for the field, so there is no way to change its
value. The field is immutable . The best you can do is to create a new instance of
class Integer with the desired value. For example, suppose variable d contains
the name of an Integer and we want to increment its wrapped variable. We can-
not, but we can assign to d the name of a new folder with the desired value:
d= new Integer(d.intValue() + 1);
To make this point clear, to the left in Fig. 5.1 we show variable d and the fold-
er whose name d contains. To the right, we show the state after execution of this
assignment to d .
Instance methods of class Integer
Above, we showed how an instance of class Integer wraps an int value.
You also saw the uses of constructor Integer( int ) and getter function
d a1
d a2
Figure 5.1:
Variable d before and after the assignment to it
Search WWH ::

Custom Search