1
public class Node {
  public Node right;
}

public class SpecialNode extends Node {
  public String specialLabel;
}

public class Testmain {
  public static void main(String[] args) {
  Node n1 = new Node();
  Node n2 = new Node();
  Node n3 = new Node();
  n1.right=n2;
  n2.right=n3;

  // some calculations --> now n2 has to become a SpecialNode, how ???
  }
} 

I am realizing a single linked list with Node, where every node knows its right neighbor. I created a list: Node n1-> Node n2-> Node n3. After creating the list, it contains just elements of type Node. Now i want to tell Node n2 to be a SpecialNode in order to supply a specialLabel. After the downcast the list should look like Node n1-> SpecialNode n2-> Node n3. How can this be done?

(Note that n2 does not know its left neighbor. And note that i have to tell n2 to be special after list creation so after initializing it as a Node of the superclass, cause i need to do some calculations before deciding which node is going to be special.)

2 Answers2

3

You can't tell n2 to be a SpecialNode, since it never has been.

I think you're better off trying to replace the existing n2 with a new instance of a SpecialNode. It would be a good approach to get n2 to replace itself (if it knows where it is in the list), or failing that, to at least give you a new instance of a SpecialNode. In this scenario you'd have to wire it in to n1 manually.

SpecialNode sn = n2.toSpecialNode();
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • Replacing `n2 ` with a new instance of `SpecialNode` is not an option for me, i would have to search for its left neighbor to set the `right` attribute to the new instance and delete the old node of type `Node `. The search for the left neighbor begins from the head of that list. But my list has more than 3 nodes (as in the example), i have thousands of elements in that list, I even simplified the problem, actually i have nodes in a tree. Putting a new wire will be time-consuming. – user1665066 Sep 12 '12 at 10:04
0

Here is how i solved it finally, thanks for the answer that downcasting wont work, my solution is close to the behaviour thingie @Andrew. I dont use inheritance for the Node itsself but for the data it contains. Like that Node works like a container and i keep my wires to the right neigbour. Instead of an extended SpecialNode i create an attribute for Node referencing NodeData. NodeData is extended by NodeDataSpecial, so a node can carry special content.

public class Node {
  public Node right;
  public NodeData;
}

public class NodeData {
}

public class SpecialNodeData extends NodeData {
  public String specialLabel;
}