File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt related to Generics Question 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 "Doubt related to Generics Question" Watch "Doubt related to Generics Question" New topic

Doubt related to Generics Question

Loganathan Karunakaran
Ranch Hand

Joined: Nov 04, 2008
Posts: 78
Please consider the following question and answer taken from KB Oracle Practice Exams book:

Question:Which can be inserted, independently at line 4, for the code to compile? (Choose all that apply.)

A. return e;

B. return e.getE();

C. return e2;

D. return e2.getE();

E. return new Hose().getE();

F. Compilation fails regardless of which return is inserted.

Answer:F is correct. The generic type "E", which is declared at the class level, will be associated with each instance of Hose, and is not accessible to static methods. If doStuff() was non-static, A and D would be correct.

My doubt is if doStuff() method is non-static, is the choice B correct together with A and D?

I tried removing the 'static keyword' and tried the choice B, that is "return e.getE();", but it doesn't compile. I am getting the error "cannot convert from Hose to E". The method e.getE() also returns a E, then why it is not working.

Could someone please explain this.

Thanks and regards
Loganathan. K

Andreas Svenkson
Ranch Hand

Joined: Jan 17, 2011
Posts: 179
I'm far from an expert at generics, but I believe the problem is this...

The parameterized type for Hose is E, and you have defined E to extend Hose, however you have not defined for which type it should extend Hose.

Hence, for the class E, the method E getE(); is different depending on for which type Hose is extended. As it currently stands you have extended it for its raw type, without a parametrized type.

This is hard to explain I notice... consider this, instead of your current class definition of Hose, you use:

This will make your code compile. What I tried saying above is that for the class definition I just provided, the method:

... will indeed return a class of the same type, both from class Hose and from class E. If you do not define the parameterized type for E in the class definition for Hose, as I have done above, then there is no telling what the method would return when used from the class E.

// Andreas

Loganathan Karunakaran
Ranch Hand

Joined: Nov 04, 2008
Posts: 78
hi Andreas,

Thanks for taking your time to explain this. I was also working with this question since I posted this question. I think I am in line with your explanation. Thank you.

Loganathan. k
I agree. Here's the link:
subject: Doubt related to Generics Question
It's not a secret anymore!