我有一个这样的对象列表
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);
。如果它们不是(如果您使用的是外部代码,则很可能),则不能使用子类。您可以做什么,然而,是使用组合:
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 - 在 Java 中扩展一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3666710/