• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can't understand docs.oracle Generics beginning paragraph  RSS feed

 
Winston Liek
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


Why would I get a runtime error when I pass in a string if I invoke the setter method? Isn't it String IS AN Object?
 
Rico Felix
Ranch Hand
Posts: 411
5
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will get an error if you take the following code snippet into consideration:

This is the box class that can take in any object



Now we use it to perform some operations



As we can see, since Box can take any type it is hard to keep track of the type of object currently stored and can end up casting to a wrong type thus resulting in a ClassCastException at runtime.
 
Winston Liek
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
now I see. thanks. They should have provided more explanation
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!