Wednesday, July 30, 2008

AngelikaLanger.com - Java Generics FAQs - Type Parameters - Angelika Langer Training/Consulting

AngelikaLanger.com - Java Generics FAQs - Type Parameters - Angelika Langer Training/Consulting: "Can I create an object whose type is a type parameter?
No, because the compiler does not know how to create objects of an unknown type.
Each object creation is accompied by a constructor call. When we try to create an object whose type is a type parameter then we need an accessible constructor of the unknown type that the type parameter is a place holder for. However, there is no way to make sure that the actual type arguments have the required constructors.

Example (illegal generic object creation):

public final class Pair< A , B > {
public final A fst;
public final B snd;

public Pair() {
this.fst = new A() ; // error
this.snd = new B() ; // error
}
public Pair(A fst, B snd) {
this.fst = fst;
this.snd = snd;
}
}

In the example above, we are trying to invoke the no-argument constructors of two unknown types represented by the type parameters A and B . It is not known whether the actual type arguments will have an accessible no-argument constructor."

No comments:

Post a Comment