java - Why cast after an instanceOf? -


in example below (from coursepack), want give square instance c1 reference of other object p1, if 2 of compatible types.

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

what don't understand here first check p1 indeed square, , still cast it. if it's square, why cast?

i suspect answer lies in distinction between apparent , actual types, i'm confused nonetheless...

edit:
how compiler deal with:

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

edit2:
issue instanceof checks actual type rather apparent type? , cast changes apparent type?

thanks,

jdelage

keep in mind, assign instance of square type higher inheritance chain. may want cast less specific type more specific type, in case need sure cast valid:

object p1 = new square(); square c1;  if(p1 instanceof square)     c1 = (square) p1; 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -