I get several objects of type Foo from a call to an external API. Locally I want to process those objects with a little added information so I have a subclass FooSon that adds those extra fields. How can I convert all those objects I get, to my new inherited type? Downcasting doesn't seem to be an option because those objects aren't really FooSon.
The only solution I have come up with is creating a convert function that takes the Foo object as an argument and then copies all public/protected values to a new FooSon object that is then returned.
The disadvantages are:
Class Foo doesn't implement a copy constructor or clone operator. I have the Foo source code but I would like to avoid changing it in order to keep compatibility with future releases. Nevertheless if it is the only viable alternative I would change the Foo implementation to get what I need.
FooSon could have a field in it that is a Foo. then just assign the returned value into that field. You could then create methods in Fooson that delegate their calls to the Foo field for the information that you need from the Foo from outside.
I think decorator pattern should works here:
class Foo implements FooApi {...}
class FooSon implements FooApi {
private FooApi decoratedFoo;
private String additional;
public FooSon(FooApi decoratedFoo) {
this.decoratedFoo = decoratedFoo;
}
...
}
but you can do this only if you have interface for your Foo object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With