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 Generics Question: Why Won't This Code Compile? 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 "Generics Question: Why Won Watch "Generics Question: Why Won New topic
Author

Generics Question: Why Won't This Code Compile?

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

I ran across the following code at CertPal.com



I don't understand why the code won't compile. The explanation given was that x,y & z need to be treated as instances of the Object class, but aren't they Integer, String & Double?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Well, no, they aren't. Here's their declaration:

Nothing about Integer and so on there.

Did you expect the declaration of a local variable in one of the class's methods to affect that? Why?
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

OK. But, so how are X, Y, and Z of the class Object?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

What else could they be? They aren't declared to extend or subclass anything, so Object is the only suitable erasure.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

Because you can create an instance of Erode with any X, Y and Z, the uses of x, y and z in the erode() method need to be valid for any possible X, Y and Z. You know they must be a subclass of Object, but you don't know anything else. The erode() method can't know which X, Y and Z you're going to happen to use in a particular case.
Yui Huang
Greenhorn

Joined: Apr 02, 2011
Posts: 7
Matthew Brown wrote:Because you can create an instance of Erode with any X, Y and Z, the uses of x, y and z in the erode() method need to be valid for any possible X, Y and Z. You know they must be a subclass of Object, but you don't know anything else. The erode() method can't know which X, Y and Z you're going to happen to use in a particular case.


If you limit the the type declaration to Number and String, it would compile.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

Yes, you could do that. Note that it would be pretty pointless using Y extends String, since String is final, so the only class that would allow is String (which defeats the point of being generic!).

And welcome to The Ranch!
Yui Huang
Greenhorn

Joined: Apr 02, 2011
Posts: 7
Very good point, Matt. Thank you for pointing that out. I was trying to make the code to compile.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics Question: Why Won't This Code Compile?