File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generic classes and Methods Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generic classes and Methods Problem" Watch "Generic classes and Methods Problem" New topic
Author

Generic classes and Methods Problem

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634




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 ?


OCPJP 6.0 93%
OCPJWCD 5.0 98%
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

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


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

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

Joined: Sep 26, 2010
Posts: 155
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

    OCPJP6
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Generic classes and Methods Problem
     
    Similar Threads
    Generics question (Devaka Diagnostic Exam, Question 57)
    Confused over generics
    confused with generics
    Generics from ExamLab
    How do you extend a generic abstract class