|
Authored by: Anonymous on Monday, April 23 2012 @ 11:14 AM EDT |
That's actually not true for Java. (It is true in real object-oriented
languages like Smalltalk and Self).
In Java, an int or float is a primitive value type. Instances of classes are
reference types, and those classes all derive directly or indirectly from
java.lang.Object, and the instances are heap-allocated (except if your VM is
extremely clever at optimizing the allocations). The type system lets you *use*
an int or float in places where a java.lang.Object is expected, which results in
"auto-boxing" of the primitive value type into a heap-allocated
object. In other words, an "int foo" does not have object identity,
and you can't take its address. But when it gets auto-boxed into an Integer
object, now it *does* have an object identity and this is a different identity
from some other boxed Integer (even if they contain the same value). When you
cast this Integer object back to an int, it extracts the primitive value from
inside the boxed object. So putting int and float into generic containers can
cause problems related to object identity that will be very confusing unless you
know what to expect.
The C# language does this somewhat better; the C# type system includes a type
for "struct" as a subtype of the root "object" type, and
everything derived from this "struct" type is treated as a value type.
That includes primitive value types like int/float, and also user-defined value
types like "struct Foo { ... }". The auto-boxing system is similar,
but C# generics make it easier to design types that work for any value type
(primitive or struct or whatever) without having to box it.[ Reply to This | Parent | # ]
|
|
|
|
|