0

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?

1
  • You say that you cannot change the structure of ForeighObject, however can you at least see the source code? If so it might help creating a subclass which is able to initialise itself from a ForeighObject instance. Alternatively, does the ForeighObject class have a constructor which takes another ForeighObject as an argument in order to clone it? Commented Nov 7, 2012 at 15:43

1 Answer 1

1

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..

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I solved it in that way (except I used composition). But I want to avoid this: for(ForeighObject ob : fObjects){ fobjectsWrapped.add(new ForeighObjectWrapper(ob)); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.