Search code examples
javaconstructordeep-copy

Calling constructor of subclass from constructor of superclass


I have a class 'Animal' and some subclasses of 'Animal' ('Cat', 'Dog', ...). Animal has a protected constructor and all the subclasses have a default constructor and a copy constructor.

At some point in the program I have a List of 'Animal' and I want to deep copy this list into another 'Animal' List (I mean to deep copy not only the List itself, but also all the objects in it).

To do so I wrote a function where you pass in the list to deep copy and it sets up a loop of all the elements of the list and, by using the copy constructor, adds to the new List all the elements of the old List.

The problem is that in order to call the right copy constructor I have to find out the type of 'Animal', via if... instanceof. This is not a big problem if I have few subclasses of 'Animal', but I'd prefer to create some copy constructors in the 'Animal' class which call the right subclass constructor based on the type of the argument I pass in.

But I read online that this is not possible. Is this true? And if so, is there another method apart from the if... instanceof method I'm using?


Solution

  • Your approach is wrong.

    The whole idea of good OOP is that a superclass knows nothing about child classes. Oop is about being able to add more child classes without the need to touch any other parts of your code, including the parent class.

    Rather have an abstract method deepCopy on your base class and have each child class implement that.

    So that you later can clone animals without knowing their specific class!