Cosdix
Cosdix

Reputation: 117

How to present array of objects like array of another objects

I have

class ForeighObject {...}
void someMethod(Object[]) {...}

and

ForeighObject[] fobjects = SomeStorage.getObjects();

I can manipulate only with fobjects, so I cant change neither structure of ForeighObject nor someMethod. How could override ForeighObject.toString (for example) to pass it to the someMethod without copying elements? Can I create some adapter class that could "present" ForeighObject to override only one method?

Upvotes: 0

Views: 59

Answers (1)

Mark Rhodes
Mark Rhodes

Reputation: 10217

I'm not quite sure what you mean but I guessing that someMethod makes a call to toString on the elements of the array of objects its given.

If this is the case then you can wrap each of the elements of fobjects using a wrapped subclass of ForeighObject which contains the expected toString method.

e.g.

//Subclass which wraps a ForeighObject instance..
class ForeighObjectWrapper extends ForeighObject {
    ForeighObject wrapped;
    ForeighObjectWrapper(ForeighObject toWrap){
       super(/* get values from toWrap */);
        this.wrapped = toWrap;
    }
    //Add the custom behaviour..
    public String toString(){
         return "Some custom behaviour: " + wrapped.toString();
    }
}

ForeighObject[] fobjects = SomeStorage.getObjects();  //as before..
ForeighObject[] fobjectsWrapped = new ForeighObject[fobjects.length];
for(ForeighObject ob : fObjects){
    fobjectsWrapped.add(new ForeighObjectWrapper(ob));
}

//then call someMethod on fobjectsWrapped instead of fobjects..
someMethod(fobjectsWrapped); //will invoke custom behaviour..

Note that if the someMethod also relies on the behaviour of other methods/properties of the wrapped instance then you'll need to override these methods so that they work as expected..

Upvotes: 1

Related Questions