Forums Register Login

Doubt related to Generics Question

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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

+Pie Number of slices to send: Send
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.

Regards
Loganathan. k
Villains always have antidotes. They're funny that way. Here's an antidote disguised as a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1098 times.
Similar Threads
DOUBT from scjp book
Generics question
var-args doubt clarification needed
Doubt
Another Question about Generics
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 02:24:58.