简体   繁体   中英

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> {

   }

}

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, ie 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);
  }
  ...
}

顾名思义,它是一个类型参数,因此它的范围比仅构造函数或方法还宽。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM