Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid downcasting when trying to extend a Java object

Tags:

java

oop

downcast

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:

  • Loosing information (private values)
  • Having to adapt the convert function if Foo is ever changed.

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.

like image 523
Omar Kohl Avatar asked Feb 24 '23 16:02

Omar Kohl


2 Answers

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.

like image 109
MeBigFatGuy Avatar answered Mar 09 '23 05:03

MeBigFatGuy


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.

like image 41
lukastymo Avatar answered Mar 09 '23 07:03

lukastymo