Why cast after an instanceOf?

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

    Because this particular syntactic sugar is not yet added to the language. I think it was proposed for Java 7, but it doesn't seem to have entered project coin

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 11:25

    E.g. If you hand over p1 as of type Object, the compiler wouldn't know that it is in fact an instance of Square, so that Methods etc. wouldn't be accessible. The if simply checks for a certain type to return true/false, but that doesn't change the type of the variable p1.

    0 讨论(0)
  • 2020-11-30 11:25

    The test is done to prevent from ClassCastExceptions at runtime:

    Square c1 = null;
    if (p1 instanceof Square) {
       c1 = (Square) p1;
    } else {
       // we have a p1 that is not a subclass of Square
    }
    

    If you're absolutly positive that p1 is a Square, then you don't have to test. But leave this to private methods...

    0 讨论(0)
  • 2020-11-30 11:29

    There's a difference between measuring if some object will fit in a box, and actually putting it in the box. instanceof is the former, and casting is the latter.

    0 讨论(0)
  • 2020-11-30 11:33

    Old code wont work correctly

    The implied cast feature is justified after all but we have trouble to implement this FR to java because of backward-compatibility.

    See this:

    public class A {
        public static void draw(Square s){...} // with implied cast
        public static void draw(Object o){...} // without implied cast
        public static void main(String[] args) {
            final Object foo = new Square();
            if (foo instanceof Square) {
                draw(foo);
            }
        }
    }
    

    The current JDK would compile the usage of the second declared method. If we implement this FR in java, it would compile to use the first method!

    0 讨论(0)
提交回复
热议问题