views:

97

answers:

4

Hi

I got a list of objects like this

ArrayList <Page> pageList = aForeignObject.getAllPages();

And a child class

class MyPage extends Page
{

    public void newFunction()
    {
        // A new Feature
    }
}

Is it possible somehow to convert the Page objects into MyPage objects?

I would love to do sth like this:

MyPage page = pages.get(1); // This will obviously fail 
page.newFunction();
+1  A: 
Péter Török
Unfortunately the object is an instance of Page and not of MyPage
Jan
I would love to add the function to Page however it is part of a foreign library. I also don't know how to reach the internal state of the "real" page object.
Jan
@Jan, then I am afraid you have no other choice than the [decorator](http://en.wikipedia.org/wiki/Decorator_pattern) approach proposed by @Scott. As a side note, including all this info in your original post instead of comments would have saved all of us some useless typing...
Péter Török
+4  A: 

If the Page objects coming out of the getAllPages() method are actually MyPage objects, then simply use a cast (e.g. MyPage page = (MyPage) pages.get(1);. If they're not (as is likely if you're using external code), you can't use sub classes. What you could do, however, is use composition:

class MyPage{
    private Page p;

    public MyPage(Page aPage){
        p = aPage;
    }

    public void newFunction(){
        //stuff
    }

    public Object oldFunction(){
        return p.oldFunction();
    }
}

Then you could do stuff like:

MyPage page = new MyPage(pages.get(1));
page.newFunction();
Scott
I thought about this solution however I would have to write 50 "old" functions and have to change it everytime the Page class changes
Jan
How about making it an explicit wrapper then - have a public `Page getOldPage()` method that allows the old methods to be called directly.
Scott
Guess I will do that. Thought there might be a better way.
Jan
A: 

This is obviously messy but can work...

Page page = pages.get(1);
if (page instanceof MyPage) {
  ((MyPage)page).newFunction();
}

You can hold a list of all classes that extends Page, i.e.

List <? extends Page> pageList = aForeignObject.getAllPages(); //Bear in mind that Page objects will never be found here.

Now, if the list only contains MyPage, then you can use my example above. Like I said, it's not an effective nor is it an efficient solution.

The Elite Gentleman
A: 

I think the solution is to implement your "new feature" in Page. I had also a few of these situations before and for me, implementing it in the base class was the solution. But I don't know exactly in what kind of situation your are....

Second solution (not recommend): make your "new feature" a static method. Something like this:

public static void feature(Page page)
{
     ....
}

Then, you can make a shortcut in MyPage:

public void invokeFeatureMethod()
{
     feature(this);
}
Martijn Courteaux