Search code examples
javainheritancesubclasscopy-constructorsuperclass

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. Example, say ClassA is the superclass to ClassB. You could set an element of a ClassA[] to reference a ClassB object. 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. The purpose of this method is to create and return a copy of an item in the masterInventory array. To avoid .clone(), I've created copy constructors for Collectible and 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. 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.


Solution

  • 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:

    itemToReturn = masterInventory[iterator].getCopy();
    

    the benefit here is that you do not need the condition on class.