William Jockusch
William Jockusch

Reputation: 27295

Create subclass object with factory method

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.

Upvotes: 2

Views: 157

Answers (2)

Mark H
Mark H

Reputation: 13897

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));
    }
}

Upvotes: 2

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

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);

Upvotes: 2

Related Questions