Search code examples
javainheritancedowncast

How to downcast an array in Java?


I currently have a Tile class that extends a Node class, and want to downcast an array of Nodes to an array of Tiles like so:

class Node<T> {
  Node[] neighbours;
  private final T value;
}

class Tile extends Node {

  public Tile(Point value) {
    super(value);
  }

  Tile[] neighbours = (Tile[]) this.getNeighbours;
}

At the moment the compiler is throwing A ClassCastException and I do not know how to fix it.

I am not 100% familiar with inheritance, but I thought since Tile is a subclass this should be a safe casting from Nodes to Tiles.


Solution

  • If Tile is a sub-class of Node, all Tiles a Nodes, but not all Nodes a Tiles.

    Therefore casting a Node[] to Tile[] is wrong, since not all Node arrays are Tile arrays.

    For example, the following will throw ClassCastException:

    Node[] nodes = new Node[10];
    Tile[] tiles = (Tile[]) nodes;
    

    On the other hand, the following will work:

    Node[] nodes = new Tile[10];
    Tile[] tiles = (Tile[]) nodes;