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.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).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.
This will throw a
ClassCastException
sinceItem[] itms = new Item[2];
.itms
has no instance ofMovingItem
.Outside of that, the reference of the object is stored. There's no object creation done.
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 useVector
, you should strongly consider usingArrayList<E>
instead, btw.)It stores a reference to
itms[0]
in the vector, but before it can do that, it has to check thatitms[0]
is in fact aMovingItem
. In this case, since it is not, aClassCastException
is thrown, and theVector.add()
is never even called.