用Java扩展类

我得到了这样的对象列表

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

还有一个儿童班

class MyPage extends Page
{

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

是否有可能以某种方式将Page对象转换为MyPage对象?

我很乐意做这样的事情:

MyPage page = pages.get(1); // This will obviously fail 
page.newFunction();

解决方法:

如果从getAllPages()方法中出来的Page对象实际上是MyPage对象,则只需使用强制转换(例如MyPage page =(MyPage)pages.get(1);.如果不是)(很可能是因为重新使用外部代码),则不能使用子类,但是可以使用composition:

class MyPage{
    private Page p;

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

    public void newFunction(){
        //stuff
    }

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

然后,您可以执行以下操作:

MyPage page = new MyPage(pages.get(1));
page.newFunction();
上一篇:Java多态性-具体示例


下一篇:php多态-在多态子功能中调用父功能