Casting-(Base) o- 它到底有什么作用?
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);
}
}
我很难意识到这个 (Base) o
是否改变了 o
的静态类型。我记得我在这里被告知它不会改变它,那么它有什么作用呢?为什么我需要这样做?在什么条件下以及出于什么目的?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不会改变
o
的静态类型,因为表达式o
仍然是Sub
类型 - 但表达式(Base) o
的类型为Base
。我认为您的意思可能是它不会更改o
引用的对象的类型。在这种情况下,转换为Base
根本没有任何意义。它不会改变foo()
调用的执行。然而,在各种不同的情况下,强制转换确实有意义。It's not changing the static type of
o
, in that the expressiono
is still of typeSub
- but the expression(Base) o
is of typeBase
. What I think you may mean is that it doesn't change the type of the object thato
refers to. In this case, there is no purpose in casting toBase
at all. It doesn't change the execution of thefoo()
call. There are various and different cases where casting does make sense, however.它什么也不做。在某些其他语言中,这可能会调用
Base
中定义的foo
,但在这种情况下,它仍然调用Sub.foo
It does nothing. In some other language this might call the
foo
defined inBase
but in this case it still callsSub.foo