Why cast after an instanceOf?

前端 未结 11 1885
情歌与酒
情歌与酒 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:49

    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;
    

提交回复
热议问题