ycesar
ycesar

Reputation: 440

How to instantiate a generic recursive class in Java

My problem is that I am using a class not developed by me (I took it from Microsoft Azure SDK for Java). The class is called Node and you can see it here.

As you can see the class is a generic class declared recursively like this:

public class Node<DataT, NodeT extends Node<DataT, NodeT>> {
      ...
}

When I try to instantiate it I don't know how to do it. I am doing this but I know IT IS NOT the way because it has no end:

Node<String, Node<String, Node<String, Node<...>>>> myNode = new Node<String, Node<String, Node<String, Node<...>>>>;

I hope you understand my question. Thanks.

Upvotes: 8

Views: 350

Answers (3)

khelwood
khelwood

Reputation: 59112

You can use a wildcard in your variable declaration:

Node<String, ?> n = new Node<>();

Or you can create an explicit subclass

class StringNode extends Node<String, StringNode> { }

and instantiate it via

Node<String, ?> n = new StringNode();

or

StringNode n = new StringNode();

Upvotes: 2

Harmlezz
Harmlezz

Reputation: 8068

One way is to extend Node like:

class MyNode<T> extends Node<T, MyNode<T>> {
}

and then instantiate it like:

Node<String, MyNode<String>> node1 = new MyNode<String>();

or

MyNode<Integer> node2 = new MyNode<Integer>();

Upvotes: 5

Radiodef
Radiodef

Reputation: 37845

You have to declare a class which extends Node so you can use the name of the class:

class StringNode extends Node<String, StringNode> {
}

Upvotes: 4

Related Questions