Java Reference
In-Depth Information
// Method to cause boxing conversion
public static Integer boxInteger(Integer obj) {
return obj;
}
// Method to cause unboxing conversion
public static void unboxInteger(int n) {
System.out.println("value = " + n);
}
AutoboxingInAction.java
This example produces the following output:
value = 3
value = 97
value = 55
value = 22
value = 12345
How It Works
You have defined the boxInteger() method with a parameter type of type Integer . When you call this
method in the first for loop in main() , you pass values of type int to it from the values array. Because
the boxInteger() method requires the argument to be a reference to an object of type Integer , the com-
piler arranges for autoboxing to occur by inserting a boxing conversion to convert the integer value to an
object of type Integer . The method returns a reference to the object that results, and you store this in the
Integer[] array objs .
The second for loop in main() passes each reference to an Integer object from the objs array to the
unboxInteger() method. Because you have specified the method parameter type as type int , the meth-
od cannot accept a reference to an object of type Integer as the argument directly. The compiler inserts
an unboxing conversion to obtain the value of type int that the object encapsulates. This value is then
passed to the method, and you output it.
Autoboxing is particularly useful when you need to insert values of primitive types into a collection —
you learn about the collection classes that are available in the class libraries in Chapter 14, but you see
more on boxing and unboxing conversions in Chapter 13.
CONTROLLING ACCESS TO CLASS MEMBERS
I have not yet discussed in any detail how you control the accessibility of class members from outside the
class — from a method in another class in other words. You know that you can refer to any of the static
members of the same class in the code for a static class method, and a non-static method can refer to any
member of the same class. The degree to which variables and methods within one class are accessible from
other classes is a bit more complicated. It depends on what access attributes you have specified for the
members of a class, whether the classes are in the same package, and whether you have declared the class as
public. This is why you had to understand packages first.
Search WWH ::




Custom Search