Object type

From Free net encyclopedia

In computer science, an object type (a.k.a. wrapping object) is a datatype that is used in object-oriented programming to wrap a non-object type to make it look like an object.

Some object-oriented programming languages make a distinction between objects and non-objects, often referred to as primitive types for reasons such as runtime efficiency and syntax or semantic issues. For example, Java has primitive wrapper classes corresponding to each primitive type: Integer and int, Character and char, Float and float, etc. Languages like [[C++]] make little or no distinction between objects and non-objects; thus, the use of object type is of little interest.

Boxing

Boxing is to place a primitive type within an object so that the primitive can be used as an object, in a language where there is a distinction between a primitive type and an object type. For example, lists may have certain methods which arrays might not, but the list might also require that all of its members be objects. In this case, the added functionality of the list might be unavailable to a simple list of numbers.

For a more concrete example, in Java, a Template:Javadoc:SE can change its size, but an array must have a fixed size. You might desire to have a LinkedList of ints, but the LinkedList class only lists objects – it cannot list primitive types.

To get around this, you can box your ints into Integers, which are objects, and then you can create a LinkedList of Integers. (Using generic parameterized types introduced in J2SE 5.0, this type is represented as LinkedList<Integer>.)

Autoboxing

Autoboxing is the term for treating a primitive type as an object type without any extra code.

For example, as of J2SE 5.0, Java will now allow you to create a LinkedList of ints. This does not contradict what was said above: The LinkedList still only lists objects, and it cannot list primitive types. But now, when Java expects an object but receives a primitive type, it immediately converts that primitive type to an object.

This action is called autoboxing, because it is boxing that is done automatically (and implicitly) by the computer, instead of requiring you to do it yourself.

Unboxing

Unboxing is the term for treating an object type as a primitive type without any extra code.

For example, in versions of Java prior to J2SE 5.0, the following code did not compile:

Integer i = new Integer(9);
Integer j = new Integer(13);
Integer k = i + j;

The last step, in particular, does not make much sense. Integers are objects; they are nebulous blocks of code somewhere else. What does it mean to add them? But the following code is perfectly okay:

int i = 9;
int j = 13;
int k = i + j;

As of J2SE 5.0, the first example is now treated just like the second example. The Integer is unboxed into an int, the two are added, and then the sum is autoboxed into a new Integer.ja:ボックス化