How to return an subclass with generics

By | March 5, 2016

In 2013, I created a project to provide a general-purpose tree structure in Java.

One challenge at that time (mostly because I was not an expertise at that time, neither am I now) is the return type of Tree methods. For example, the return type of getChild(int index) that should return the child at the specified index.

public class Tree<E>  {
  private E obj;
  ...
  public Tree getChild(int index) {...}
}

One way is to return Tree, but it makes difficult if we need to subclass of Tree. For example, in StringTree that extends Tree, the return type is still Tree. Ideally, we need StringTree. Of course, we can use cast Tree to StringTree every time we call the method

public class StringTree extends Tree<String>  {
}

StringTree firstChild = (StringTree)t.getChild(0);

But we can do it better.

public class Tree<E, T extends Tree<E, T>> {
  private E obj;
  ...
  public T getChild(int index) {...}
}

By this way, StringTree#getChild(int index) will return StringTree.

Leave a Reply

Your email address will not be published. Required fields are marked *