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
ClassCastExceptionas above).