将超类的对象转换为子类的对象会创建一个新对象? [英] Casting an object of a superclass into an object of a subclass creates a new object?

查看:187
本文介绍了将超类的对象转换为子类的对象会创建一个新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个父类Item和一个子类MovingItem。

Suppose I have a superclass Item and a subclass MovingItem.

如果我创建一个项目数组,然后尝试将一个已创建的项目转换为一个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]);

当我在数组itms中找到类型Itm的对象的索引为0时会发生什么,然后存储它在向量?我存储一个引用或转换创建一个类型MovingItem的新对象,然后将其添加到向量。

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.

谢谢。

推荐答案

您的示例将抛出 ClassCastException

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

当然,一个对象不创建一个新的对象,它只创建一个新的引用(如果转换不会失败,并且如上所述 ClassCastException )。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆