Niall
Niall

Reputation: 1621

How to copy an object when only its abstract base class is known

I have an abstract base class MusicTime, which has several concrete subclasses - Quaver, SemiQuaver, Crotchet etc. The subclass instances are contained in a List<? extends MusicTime> collection.

I need to be able to clone these objects, and am doing this manually by iterating through the collection and creating new instances based on the existing instance. I obviously can't instantiate an abstract class, so is there any way of calling the constructor of the same MusicTime constructor as each existing instance? So if it's a Quaver then I create a new Quaver object?

Upvotes: 0

Views: 158

Answers (2)

B.J. Smegma
B.J. Smegma

Reputation: 304

I see a clean and a dirty solution:

  • implement the clone() (from the Cloneable interface) method for each of the classes in the hierarchy (clean solution)
  • use instanceof operator to find out which class is the object instance of (dirty solution)

    Upvotes: 3

  • Prakash
    Prakash

    Reputation: 4617

    I believe you can use Prototype design pattern, with that you can add

    abstract MusicTime clone()
    

    in your MusicTime base class, and implement in all the subclasses which create its own object. When you iterate through list call clone.

    http://www.codeproject.com/Articles/42582/Prototype-Design-Pattern

    http://java.dzone.com/articles/design-patterns-prototype

    Upvotes: 1

    Related Questions