简体   繁体   English

Java超类变量和子类复制构造函数问题

[英]Java superclass variable and subclass copy constructor issue

I know that in Java due to inheritance, a superclass type variable can hold a reference to a subclass object. 我知道在Java中,由于继承,超类类型变量可以保存对子类对象的引用。 Example, say ClassA is the superclass to ClassB. 例如,假设ClassA是ClassB的超类。 You could set an element of a ClassA[] to reference a ClassB object. 您可以设置ClassA []的元素以引用ClassB对象。 I'm running into a problem doing this while using a copy constructor of the subclass. 我在使用子类的副本构造函数时遇到问题。

public Items copyFromMasterInventory(String str){
        Items itemToReturn = null;
        int length = masterInventory.length;
        int iterator = 0;
        while (iterator < length){
            String name = masterInventory[iterator].getName();
            if (name.equals(str)){
                if (name.getClass().equals(Collectible.class)){
                    itemToReturn = new Collectible(masterInventory[iterator]); 
                 }
                if (name.getClass().equals(Props.class)){
                    itemToReturn = new Props(masterInventory[iterator]);
                }
            }
        }
        return itemToReturn;
    }

In this case, there are three class. 在这种情况下,分为三类。 Items, Props, and Collectible. 物品,道具和收藏品。 Props and Collectible are subclasses of Items. 道具和收藏品是物品的子类。 masterInventory is an array of Items storing both Collectible and Props objects. masterInventory是一组同时存储Collectible和Props对象的Items数组。 The purpose of this method is to create and return a copy of an item in the masterInventory array. 此方法的目的是在masterInventory数组中创建并返回项目的副本。 To avoid .clone() , I've created copy constructors for Collectible and Props. 为了避免.clone() ,我为Collectible和Props创建了副本构造函数。 But the way I have it now shows an incompatible types error, that Items cannot be converted to Collectible or Props, even though the object stored in that element is a Collectible or Props object. 但是我现在拥有的方式显示了一个不兼容的类型错误,即使存储在该元素中的对象是Collectible或Props对象,Item也无法转换为Collectible或Props。 If been reading and searching for hours but can't seem to come up with a solution. 如果正在阅读和搜索数小时,但似乎无法提出解决方案。 Does anyone know a way around this issue? 有人知道解决此问题的方法吗? All help is appreciated. 感谢所有帮助。

The solution is simple - casting : 解决方案很简单-铸造:

if (masterInventory[iterator] instanceof Collectible) {
    itemToReturn = new Collectible((Collectible) masterInventory[iterator]); 
}
if (masterInventory[iterator] instanceof Props) {
    itemToReturn = new Props((Props) masterInventory[iterator]); 
}

You could add an abstract method Item getCopy() to the Item class, implement it in both Props and Collectible, and call it in de while loop: 您可以将抽象方法Item getCopy()到Item类,在Props和Collectible中都实现它,然后在while循环中调用它:

itemToReturn = masterInventory[iterator].getCopy();

the benefit here is that you do not need the condition on class. 这样做的好处是您不需要上课的条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM