Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading