javaoopfactoryextending-classes

Initialize extended class through base class factory in Java


It's my first question here so please don't be angry at me if something wrong.

Here is the problem: We have class Node. It's a base class for class Item. So basically:

public class Item extends Node

Ok, still everything is fine. But we also have class let's call it NodeFactory that contains static method loadNodeAssets returning Node as a result.

 public static Node loadNodeAssets (String path)

In the library I am using it is only way to initialize Node class and load assets into it. But the main problem is that I need to get Item class instance but not Node. How could I accomplish it?

 Item f = (Item)NodeFacory.loadNodeAssets ("...")

Not working since returning class has type Node but not Item. Basically I need to construct Fish class and initialize inherited fields in the Node class which Fish class extending. Sorry for my english. Hope for your help. Thank you!


Solution

  • First you should find out what class you are actually getting back:

    Node n = NodeFacory.loadNodeAssets ("...")
    System.out.println(n.getClass());
    

    If it turns out to be a Node then your only way of getting an Item will be to construct it manually:

    Node n = NodeFacory.loadNodeAssets ("...")
    Item i = new Item();
    i.setAAA(n.getAAA());
    i.setBBB(n.getBBB());
    

    If the library doesn't allow you to construct Items at all, then there are only two possibilities:

    1. You misunderstand how the library should be used. Maybe you think you need an Item but you really only need a Node.
    2. The library's design is bogus. In this case you should probably look for alternatives, or - if you have the source code - fix it yourself.