Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic classes and Methods Problem

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



The above code compiles fine.

i think it should not because
if i define

then ,integer extends Number,so it fulfills the generic class defination
but in the function useMe,the return type is A<? super Number>
And integer doesnot full fill the condition as it's not super type of Number.

THen ,why does the code compiles fine ?
 
Ankit Garg
Sheriff
Posts: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a new K defined with the method. The above code is similar to this
Also the reason you think this code should not compile is not right. The method useMe can return an object of A which has a different type than the object that you called it through. So if you call the useMe through A<Integer>, the method can actually return an A<Number> ...
 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
he method useMe can return an object of A which has a different type than the object that you called it through. So if you call the useMe through A<Integer>, the method can actually return an A<Number> ...




so,i can use anything in the line1(text in bold)
eg.




Doesn't class A<K extends Number> imposes restriction on methods returning A to be of generic type K extends Number ?
e.g:
abstract A<? super Number> useMe();//wrong
 
Trivikram Kamat
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohitkumar gupta wrote:
Doesn't class A<K extends Number> imposes restriction on methods returning A to be of generic type K extends Number ?


The generic parameter used in class definition may not implement restriction on any argument or return variable of instance method.

The wildcard ? in: just tells that the object is A of <? extends Number> which can be:
  • A<Number>
  • A<Integer>
  • A<Long>
  • A<Double>
  • etc


  • You may get error while running the code, if the type doesn't match as defined in the method definition.
    But, it may not be related to generic parameter used in class definition
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic