Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cast after an instanceOf?

In the example below (from my coursepack), we want to give to the Square instance c1 the reference of some other object p1, but only if those 2 are of compatible types.

if (p1 instanceof Square) {c1 = (Square) p1;} 

What I don't understand here is that we first check that p1 is indeed a Square, and then we still cast it. If it's a Square, why cast?

I suspect the answer lies in the distinction between apparent and actual types, but I'm confused nonetheless...

Edit:
How would the compiler deal with:

if (p1 instanceof Square) {c1 = p1;} 

Edit2:
Is the issue that instanceof checks for the actual type rather than the apparent type? And then that the cast changes the apparent type?

like image 915
JDelage Avatar asked Nov 15 '10 16:11

JDelage


1 Answers

Keep in mind, you could always assign an instance of Square to a type higher up the inheritance chain. You may then want to cast the less specific type to the more specific type, in which case you need to be sure that your cast is valid:

Object p1 = new Square(); Square c1;  if(p1 instanceof Square)     c1 = (Square) p1; 
like image 52
Justin Niessner Avatar answered Sep 21 '22 15:09

Justin Niessner