gstackoverflow
gstackoverflow

Reputation: 37034

generic method declaration within generic class. Boundaries allowing different for super and without it

What wrong in this method declaration?

public abstract class A<K extends Number>{  
   public abstract <K> A<K> useMe (A<K> k);
}

I see compile error:

java: type argument K is not within bounds of type-variable K

my first thought for this compile error was that as - It is not guaranteed that K is Number in my method declaration, that's why issue is coming.

But in another case as below:

public abstract <K> A<? extends Number> useMe (A<? super K> k);

A<? super K> is again not guaranteed that it is Number (However IDE sign warning) but it is not compile error.

What are the differences?

Upvotes: 2

Views: 154

Answers (2)

Karsan
Karsan

Reputation: 269

remove extends Number from class and add it with method i.e. public abstract class A<T>{ public abstract <T extends Number> A<T> useMe(A<T> t); }

Upvotes: 1

svz
svz

Reputation: 4588

Ok, here's a different answer. The reason is that though you use <K> as a generic in your method, it has nothing to do with the <K> you used in your class. It would be more obvious if you wrote

abstract class A<K extends Number>{
    public abstract <T> A<T> useMe(A<T> t);
}

Here <T> is some generic, but you have limited A to only use generics which extend Number and <T> in this case doesn't and it fails to implement the contract of A. Here is where the error comes from. For that reason you should write

abstract class A<K extends Number>{
    public abstract <T extends Number> A<T> useMe(A<T> k);
}

Upvotes: 0

Related Questions