• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Question: Why Won't This Code Compile?

 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK. But, so how are X, Y, and Z of the class Object?
 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What else could they be? They aren't declared to extend or subclass anything, so Object is the only suitable erasure.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very good point, Matt. Thank you for pointing that out. I was trying to make the code to compile.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic