Why cast after an instanceOf?

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

    The compiler does not infer that since you are in the block, you have done a successful check for the type of the object. An explicit cast is still required to tell the compiler that you wish to reference the object as a different type.

    if (p1 instanceof Square) {
        // if we are in here, we (programmer) know it's an instance of Square
        // Here, we explicitly tell the compiler that p1 is a Square
        c1 = (Square) p1;
    }
    

    In C# you can do the check and the cast in 1 call:

    c1 = p1 as Square;
    

    This will cast p1 to a Square, and if the cast fails, c1 will be set to null.

提交回复
热议问题