开发者

Java Generics .. Type parameter not allowed after class name on the constructor header

Just wonder why type parameter are not allowed after the class name on the constructor. I mean what's the reason behind this. Is it becos' the type parameter already defined on the class header and so doesn't make sense to have it on the constructor?

Class A <E> {

   public E e;

   A <E> {

   }

开发者_JAVA百科}

Just curious


You can define type parameters for a constructor, using the same syntax used for methods.

However, it's important to realize this is a new type parameter, visible only during execution of the constructor; if it happens to have the same name as a type parameter on the class, it will hide that parameter in the larger scope.

class Foo<T>
{
  <T> Foo(T bar) /* This "T" hides the "T" at the class level. */
  {
    ...


If you define generics in class level they must be declared during declaration of class.

class A<T>{}

Do you want to declare T when declaring constructor, i.e. something like this:

class A {
    public A<T>() {
    }
}

But in this case you cannot use T before constructor when you wish to declare fileds:

class A {
    private T t; // this will throw compilation error: T is undefined. 
    public A<T>() {
    }
}

I think that this is the reason that Sun defined existing syntax for generics.

Although you can use generic type as parameter of constructor:

class A<T> {
    public A(T t) {
    }
}


Well, at least the following seems to compile in Eclipse:

public class A{
      private boolean same;

  public <T> A(T t1, T t2, Comparator<? super T> comparator){
    this.same = (comparator.compare(t1, t2) == 0);
  }
  ...
}


As the name says, it is a type parameter, and so its scope is wider than just a constructor or a method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜