Object aThing = new Integer(25);
According to my text book, the expression (Integer) aThing casts the type of the object referenced by aThing(type Object) to type Integer. The casting operation will succeed only if the object referenced by aThing is, in fact type Integer; if not, a ClassCastException will be thown
I don’t understand what the bolded sentence is saying. Can you briefly elaborate on that?
what is the “object referenced by aThing“?
Now since
aThingreference points to anInteger object. So, you can cast that reference to anInteger. Because anintegerreference can point to anIntegerobject.But when you try to typecast that reference to a
Stringreference, then you will getClassCastExceptionbecause, a String is not anInteger, and hence cannot contain a reference to anIntegerobject.