Wildcards
How to write a generic interface with List of implemented classes of the interface?
I encounter this problem when I write a tree node interface, here are the details of the problem: I need to create an interface for the following two classes, how to write the interface?
public class TreeNode<T> {
private T data;
private List<TreeNode<T>> children;
public T getData() {
return this.data;
}
public List<TreeNode<T>> getChildren() {
return this.children;
}
}
public class DoubleLinkedTreeNode<T> {
private T data;
private List<TreeNode<T>> children;
private DoubleLinkedTreeNode<T> parent;
public T getData() {
return this.data;
}
public List<DoubleLinkedTreeNode<T>> getChildren() {
return this.children;
}
}
Both classes have getData
and getChildren
method, and they are the methods interface need to define. However, the tricky part is how to represent the TreeNode
or DoubleLinkedTreeNode
in their interface? The answer is wildcards, here is the interface:
public interface TreeNodeInterface<T> {
T getData();
List<? extends TreeNodeInterface<T>> getChildren();
}
You can view my explanation here
Top comments (0)