• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics and Object Types.  RSS feed

 
Gary Charles
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to learn Generics from the Sun/Oracle Java Trails here: Generic Types. The section says:
A Simple Box Class
Begin by examining a non-generic Box class that operates on objects of any type. It needs only to provide two methods: set, which adds an object to the box, and get, which retrieves it:

Since its methods accept or return an Object, you are free to pass in whatever you want, provided that it is not one of the primitive types. There is no way to verify, at compile time, how the class is used. One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error.
(emphasis mine)

So I've tried to create a class that will generate a runtime error so I can better understand the concept but I haven't been able to get a runtime error as described above. Here's my code. Why is this working when the text above says it might generate a runtime error?


In BoxObjectTest, on line 09 I pass in a number and on line 13 I pass in a string. Both provide output just fine and I don't get a runtime exception. My output is:

What am I missing?

Thanks,
Gary
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you've done is add an Integer, and then treat it like an Integer when you take it out again. Then you add a String, and treat it like a String. That's always going to be fine. The problem arises when you add one type, and try to cast it to another type.

Try commenting out lines 10-13 from your test code, and run it again. Then you'll be adding an Integer and casting it to a String. That will be a runtime error. Whereas using a generic class the compiler would catch it.
 
Gary Charles
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew. So then one way to use this would be something like below, where you create separate objects for the int and string?



 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup, you got it.

(For extra points: write some similar code which gives compiler errors. Then you'll be sure you got it.)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!