Why cast after an instanceOf?

前端 未结 11 1869
情歌与酒
情歌与酒 2020-11-30 11:05

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 i

11条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 11:39

    The variable p1 has whatever type it started with - let's say Shape. p1 is a Shape, and only a Shape, no matter that its current contents happen to be a Square. You can call - let's say - side() on a Square, but not on a Shape. So long as you are identifying the entity in question via the variable p1, whose type is Shape, you can't call side() on it, because of the type of the variable. The way Java's type system works, if you can call p1.side() when you happen to know it's a Square, you can always call p1.side(). But p1 can hold not just Square Shapes, but also (say) Circle Shapes, and it would be an error to call p1.side() when p1 held a Circle. So you need another variable to represent the Shape which you happen to know is a Square, a variable whose type is Square. That's why the cast is necessary.

提交回复
热议问题