Java class extension

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 to somehow convert page objects to MyPage objects?

I would like to do this:

MyPage page = pages.get(1); // This will obviously fail 
page.newFunction();
+3
source share
4 answers

If the objects Pageexiting the method getAllPages()are actually objects MyPage, then just use a listing (e.g. MyPage page = (MyPage) pages.get(1);). If they are not (as possible, if you use external code), you cannot use a subclass. However, you can use usage composition:

class MyPage{
    private Page p;

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

    public void newFunction(){
        //stuff
    }

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

Then you can do things like:

MyPage page = new MyPage(pages.get(1));
page.newFunction();
+4
source

A short solution is casting:

MyPage page = (MyPage)pages.get(1);

, , MyPage - ClassCastException. , :

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

, downcasts , . aForeignObject.getAllPages() MyPage, . , newFunction Page ( ), ; newFunction Page .a >

:, Page, MyPage... :

class MyPage extends Page {
  MyPage(Page other) {
    // deep copy internal state
  }
  ...
}

, , , . , , .

+1

, ...

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

, extends Page, ..

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

, MyPage, . , .

0

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

Second solution (not recommended): make your "new function" a static method. Something like that:

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

Then you can make a shortcut in MyPage:

public void invokeFeatureMethod()
{
     feature(this);
}
0
source

Source: https://habr.com/ru/post/1763767/


All Articles