开发者

Why cast after an instanceOf?

开发者 https://www.devze.com 2023-01-25 08:44 出处:网络
In the example below (from my coursepack), we want to give to the Square instance c1 the reference of some other object p1, but on开发者_StackOverflow中文版ly if those 2 are of compatible types.

In the example below (from my coursepack), we want to give to the Square instance c1 the reference of some other object p1, but on开发者_StackOverflow中文版ly if those 2 are of compatible types.

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

What I don't understand here is that we first check that p1 is indeed a Square, and then we still cast it. If it's a Square, why cast?

I suspect the answer lies in the distinction between apparent and actual types, but I'm confused nonetheless...

Edit:

How would the compiler deal with:

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

Edit2:

Is the issue that instanceof checks for the actual type rather than the apparent type? And then that the cast changes the apparent type?


Old code will not 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

精彩评论

暂无评论...
验证码 换一张
取 消