objIn.readObject();
Returns a reference of type Object
. You can not assign a reference of type Object
, to a reference declared as type Pet
. So you use this syntax to cast it. Casting is changing the type of something. In this case, the pointer to the existing Object
.
Example
Object obj = objIn.readObject();
if(obj instanceof Pet) {
// Make sure it is of type Pet
Pet pet1 = (Pet)obj;
}
The (Pet)
tells the compiler to now refer to this instance as a type of Pet
.
Edit
I couldn't put it better myself, so Andrzej's comment can go here:
Casting only tells the type-checker that you (the programmer) have more information about the real type of the object, than can be inferred from static typing. In this example for instance, readObject is only guaranteed to return an Object - but we can tell from the context that the returned value will actually, in reality, be an instance of Pet.