2

There is a class Gold which I do not control. It has a factory method:

public static Gold TransmuteFromLead(Lead someLead);

I am now subclassing Gold to make my own class GoldWatch. I have a Lead object. Is there a way to write a TransmuteFromLead method in GoldWatch that somehow uses Gold's TransmuteFromLead method but makes a GoldWatch object?

For a similar but not-quite-the-same question, see What's the correct alternative to static method inheritance? But my situation is different, because I don't control the base class.

Community
  • 1
  • 1
William Jockusch
  • 26,513
  • 49
  • 182
  • 323
  • If you had a GoldWatch CreateWatch(Gold someGold) method on GoldWatch, you could create the gold then create the watch. I can't think of a good way to directly create it. – Maess Feb 24 '14 at 16:12
  • Even though it might be handy once in a while, there's no simple way. You have to create the transformation from either `Lead` or `Gold` manually. This may very well be impossible (in a clean way) if you also need to copy some private fields. The core issue is that even though some of the data is shared between `Gold` and `GoldWatch`, they're two different objects in the end. Things like their memory organization is an implementation detail of the JIT compiler, so there really isn't anything to go by. If you really need to do this, you might have to use reflection, and it will still be tricky. – Luaan Feb 24 '14 at 16:22

2 Answers2

2

You could use an implicit operator:

public static implicit operator GoldWatch(Gold g)
{
    return new GoldWatch(g);
}

and then add a constructor on the GoldWatch to initiate itself from a Gold object.

This would allow you to do this:

var goldWatch = (GoldWatch)TransmuteFromLead(someLead);

or even this:

GoldWatch goldWatch = TransmuteFromLead(someLead);
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
2

For any additional public methods in Gold, you wrap them in GoldWatch and just call the same method on the gold instance.

class GoldWatch : Gold {
    Gold gold;

    private GoldWatch(Gold gold) {
        this.gold = gold;
    }

    GoldWatch TransmuteFromLead(Lead someLead) {
        return new GoldWatch(Gold.TransmuteFromLead(someLead));
    }
}
Mark H
  • 13,797
  • 4
  • 31
  • 45