lqdev
lqdev

Reputation: 403

How to clone an object from an array of objects with different types

I've got this code:

int width = 1280;
int height = 720;

List<ElectronicDevice> devices = new ArrayList<ElectronicDevice>();

class ElectronicDevice {
  int x;
  int y;
  // ...
}

class EClock extends ElectronicDevice {
  int hz;

  EClock(int x, int y, int clock) {
    this.x = x;
    this.y = y;
    this.hz = hz;
  }
  // ...
}

class EBulb extends ElectronicDevice {
  EClock(int x, int y) {
    this.x = x;
    this.y = y;
  }
  // ...
}

class ToolbarElement {
  ElectronicDevice dev;

  ToolbarElement(ElectronicDevice dev) {
    this.dev = dev;
  }

  public void addDevice() {
    // somehow add a copy of `dev` to the `devices` list
  }
}

List<ToolbarElement> elements = new ArrayList<ToolbarElement>();

elements.add(new EClock(width/2, height/2, 5));
elements.add(new EBulb(width/2, height/2));

elements.get(0).addDevice();

I need to add a copy of ToolbarElement dev to devices, but I don't know how. It needs to be a deep copy. In the program I don't know the constructors of all devices, I'd like to just deep clone dev into devices.

I tried adding implements Cloneable to the ElectronicDevice class, but then I would need to add that and a clone() method to every class that extents ElectronicDevice.

After adding the implements Cloneable to ElectronicDevice it mostly worked, but all the clocks had desynchronized after adding more than 1 of them (this is a graphical application in Processing, every class that extends ElectronicDevice can have a behavior() method which specifies how it behaves and the clock oscillates between 0 and 1 with the frequency of hz Hz.)

This was my addDevice() implementation:

// In ElectronicDevice
class ElectronicDevice implements Cloneable {
  // ...
  protected Object clone() throws CloneNotSupportedException {
    return super.clone();
  }
  // end of class code
}

// In ToolbarElement
class ToolbarElement {
  // ...
  public void addDevice() {
    try { devices.add((ElectronicDevice)object.clone()); }
    catch (CloneNotSupportedException e) { e.printStackTrace(); }
  }
  // end of class code
}

Is there any solution that wouldn't require modifying every single class that extends ElectronicDevice?

Upvotes: 0

Views: 66

Answers (0)

Related Questions