Luk*_*mit 2 java casting subclass object superclass
对不起,如果以前出现过,但我没有看到另一个关于此的帖子.但如果有,请给我链接.
在这里,我有一个简单的程序.当它运行时,打印出"6 4"
public static void main(String[] args) {
Foo foo = new Foo();
foo.t = 6;
foo.f = 4;
Bar b = new Foo();
ArrayList<Bar> list = new ArrayList<Bar>();
list.add((Bar) foo);
Foo foo2 = (Foo) list.get(0);
System.out.println(foo2.t + " " + foo2.f);
}
static class Bar {
int t;
}
static class Foo extends Bar {
int f;
}
Run Code Online (Sandbox Code Playgroud)
这看起来很奇怪,因为我认为当我将Foo添加到列表中时,它会删除f字段,因为列表中包含没有f的Bars.
但似乎f在被投入酒吧之后仍然存在.有人可以解释为什么会这样吗?
即使你施放和取消它多次,实际物体也会保持不变.
转换从不添加/删除/更改对象属性.
Bar b = new Foo();
Run Code Online (Sandbox Code Playgroud)
这里引用的是类型Bar
,实际的对象是类型Foo
.作为Foo
扩展Bar
,这意味着它具有属性f
和t
(继承自Bar
).
list.add((Bar) foo);
Run Code Online (Sandbox Code Playgroud)
在这里,您将它投射到Bar(Upasting)但实际对象不会更改.
(Foo) list.get(0);
Run Code Online (Sandbox Code Playgroud)
在这里,您将它转换回Foo
静止对象是Foo
具有原始值的类型t
和f
.
归档时间: |
|
查看次数: |
135 次 |
最近记录: |