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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With