Suppose I have a superclass Item and a subclass MovingItem.
If I create an array of items and then try to cast one of the already created items into a MovingItem and store it in to a vector, does it mean I use a reference or I create a new object, for instance.
Item[] itms = new Item[2];
itms[0] = new Item();
itms[1] = new Item();
Vector<MovingItem> movingItms = new Vector<MovingItem>();
movingItms.add((MovingItem) itms[0]);
What happens when I cast the object of type Itm found in array itms at index 0 and then store it in to the vector? Do I store a reference or casting creates a new object of type MovingItem and then adds it to the vector.
Thanks.
Your example will throw a ClassCastException
. You can cast or assign object only to its actual type or any of its supertypes, but not to its subtype.
Item i = new MovingItem(); // ok, because a MovingItem is an Item
// a cast is possible, but redundant in this place
MovingItem mi = new Item(); // won't compile, an Item isn't a MovingItem
MovingItem mi = (MovingItem) new Item(); // throws ClassCastException
// an Item isn't a MovingItem
Of course, casting an object doesn't create a new object, it only creates a new reference to it (if the cast doesn't fail with a ClassCastException
as above).
Object o = new Integer(5); // assign an Integer instance to an Object variable
Integer i = (Integer) o; // cast and assign to a new Integer variable
// still points the the same actual instance
assert i == o; // true, these two variables point to the same Integer instance
It always stores a reference - no new object is created. The value of the cast is always actually the same value - it's a reference to the same object, it's just that the VM will have validated that the reference really is a reference to an instance of the subclass.
Don't forget the Vector
doesn't contain objects - it only contains references. (Unless you have a particular reason to use Vector
, you should strongly consider using ArrayList<E>
instead, btw.)
This will throw a ClassCastException
since Item[] itms = new Item[2];
. itms
has no instance of MovingItem
.
Outside of that, the reference of the object is stored. There's no object creation done.
Casting never creates new objects. It just tells the compiler that, yes, it can trust us, we know what we are doing... Funny thing is that if we are wrong, we get a runtime error at assignment time...
Side note: don't use Vector, use the faster and more modern ArrayList.
It stores a reference to itms[0]
in the vector, but before it can do that, it has to check that itms[0]
is in fact a MovingItem
. In this case, since it is not, a ClassCastException
is thrown, and the Vector.add()
is never even called.