How to make a class itself generic?

class Node {
  List<Node> children;
}

class TreeNode extends Node {
  @Override
  List<TreeNode> children; // ERROR: could not override writer method.
}

Is there a way to make generic so that:

treeNode.children is List<TreeNode>

>Solution :

Create an abstract Node class with a generic type parameter T. This T will represent the type of children nodes:

abstract class Node<T extends Node<T>> {
  List<T> children;
}

T extends Node<T> means that T should be a subtype of Node<T> itself.

Now, let’s create a TreeNode class that extends Node and specifies TreeNode as the type parameter:

class TreeNode extends Node<TreeNode> {
  @override
  List<TreeNode> children;
}

In this case, TreeNode extends Node<TreeNode>, so the children list will be of type List<TreeNode>, as you wanted. This way, you’re not overriding the children property with a different type, but specializing the Node class for TreeNode instances.

Leave a Reply