I’m looking over the code in generics. I’m tyring to understand the code but couldn’t make sense about the usage of parameterized usage of T. Why T has to be used at all why not make it to work with E and R. As far as I understand E refers element and R refers to Tree. Coudn’t make up the usage of generics in the code. Please someone expalin the code.
abstract class Tree<E> {
public interface Visitor<E, R> {
public R leaf(E elt);
public R branch(R left, R right);
}
public abstract <R> R visit(Visitor<E, R> v);
public static <T> Tree<T> leaf(final T e) {
return new Tree<T>() {
public <R> R visit(Visitor<T, R> v) {
return v.leaf(e);
}
};
}
public static <T> Tree<T> branch(final Tree<T> l, final Tree<T> r) {
return new Tree<T>() {
public <R> R visit(Visitor<T, R> v) {
return v.branch(l.visit(v), r.visit(v));
}
};
}
}
The generic type
<E>in this class is not visible for Class’s static method or fields. So you are able to replace the<T>with<E>, it’s only a name, but actually this<E>in the static method is different from theTree<E>. You can try to change the signature as below to get the compile time error message.To remove the ambiguity, it’s much better to use a different generic type name in the static method.