开发者

Casting-(Base) o- What does it really do?

class Rectangle {}

class ColoredRectangle extends Rectangle {}

class Base {
    void foo(Rectangle x) {
        System.out.println("Base: foo(Rectangle)");
    }
}开发者_运维知识库

class Sub extends Base {
    @Override
    void foo(Rectangle x) {
        System.out.println("Sub: foo(ColoredRectangle)");
    }
}

public class WhatHappensHere {

    public static void main(String[] args) {
        Sub o = new Sub();
        Rectangle rc = new ColoredRectangle();

        ((Base) o).foo(rc);
    }
}

I'm having a hard time realize if this (Base) o changes the static type of o. I remember that I was told here that it doesn't change it, so what does it do? why do I need to do that? in what conditions and for what purpose?

Thanks


It's not changing the static type of o, in that the expression o is still of type Sub - but the expression (Base) o is of type Base. What I think you may mean is that it doesn't change the type of the object that o refers to. In this case, there is no purpose in casting to Base at all. It doesn't change the execution of the foo() call. There are various and different cases where casting does make sense, however.


It does nothing. In some other language this might call the foo defined in Base but in this case it still calls Sub.foo

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜