This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
For passing "10" along with Integer constructor- As 10 string is parse able to integer its successful. You can try passing "ten" or some other string to get an ParseException.
The second query- Class cast exception- As the reference is actually an Integer, so casting it to Integer doesnt cause an exception. If it were some object of other class- say String you would get a classcast exception when you tried to cast.
Also before every cast- an instance of check is required so that you dont end up with ClassCastExceptions.
Aditya Jha wrote:Think about it... what kind of object are you actually passing in IntegerBox.add method?
it returns 10
That's not quite what he's getting at. This is happening:
- You pass a String into an Integer constructor (check the API and you'll see this constructor exists)
- This results in an Integer object
- The Integer object is passed into the IntegerBox.add method
- Which means the object contained by IntegerBox is an Integer - Which means the cast back to an Integer works fine