• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Generic classes

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
This is kind of taken from
http://www.javabeat.net/javabeat/scjp5/mocks/Generics-part3-10questions.php

I am not able to understand why Sun Engineers have problem with following class . I get compile error.

class GenTest<T super Number> {

T num;

public T checkNumber(T n) {

return n;

}

}

Where as the following class does not give compile error.

class GenTest<T extends Number> {

T num;

public T checkNumber(T n) {

return n;

}

}


With wild card ? both super and extends work . However with generic classes super seem to give compile error.

Can anybody provide some explanation ?
[ October 09, 2007: Message edited by: Akhil Maharaj ]
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy!

The lower bound wildcard <T super SomeThing> is for methods only.

It was made for a collection where - despite of the fact that the type is unknown - you can add() something to it.
Because you know that the most specific type you can put in such a collection would be of type "SomeThing".


But compared to methods, a class with such a bound wildcard as in yours
class GenTest<T super Number> { ...

cannot be allowed.
Because the variable "num" in your example then could be of Number or an Object type.
That would not make much sense, as you could not invoke Number-specific methods on an object of type Object (which - if super were allowed here - could be a possible type of GenTest).

Compared to this forbidden situation,
class GenTest<T extends Number> { ...

is ok. The type could be only Number and subclasses thereof.
So with variable "num" you could call all Number-specific methods, since subclasses are always sure to have all methods the superclass has as well.

Yours,
Bu.
reply
    Bookmark Topic Watch Topic
  • New Topic