0

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!

Serj.by
  • 534
  • 5
  • 17
  • 2
    Well, just because `Item extends Node` it does not mean that all `Nodes` are `Items` (the reverse would be true, though) so you cannot automatically cast a `Node` into an `Item` (it could be any other object that does not resemble an `Item` at all) - Instead, you may need to copy the needed fields (attributes) manually or with the aid of a property-mapping library – blurfus Dec 29 '14 at 21:51

1 Answers1

2

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.
Tilo
  • 3,255
  • 26
  • 31