2

我试图做类似的事情

class O has a child E

我声明变量

O xyz = new E();

但是如果我调用 xyz.method(),我只能调用 O 类的方法,而不是 E 的方法,所以我可以通过

E xyz2 = (E) xyz;

我的问题是——你能在不声明新变量的情况下做到这一点吗?就像是:

O xyz = new E();
xyz = (E) xyz; 

现在我可以使用 xyz.method() 来调用 E 的方法

有没有办法在java中做到这一点?

4

4 回答 4

7

yes you can downcast

((E)xyz).method();
于 2011-01-31T05:46:45.907 回答
1

No, you cannot change the type of a variable after it is declared.

You can inline the typecasts, which saves some typing if you only need to downcast once:

Number n = 1;
((Integer)n).someIntegerMethod();

You should probably create a new variable if you need to do that more than once, though. The compiler may or may not be clever enough to optimize this properly otherwise (and you would incur the runtime overhead of repeated class casting).

于 2011-01-31T05:48:19.213 回答
0

if the parent class (O) had a method xyz as well, the you could just call

O xyz = new E();
xyz.method();   // E's xyz would be called

This is polymorphism

于 2011-01-31T05:47:12.960 回答
0

你不能这样做:

O xyz = new E();
xyz = (E) xyz; 
xyx.someEMethod(); // compilation error

原因是 Java 对象的类型转换实际上并没有改变任何值。相反,它们针对对象的实际类型执行类型检查。

您的代码检查 的值xyz是否为 a E,然后将类型转换的结果分配回xyz(第二条语句),从而将其向上转换回 a O

但是,您可以这样做:

((E) xyx).someEMethod(); // fine

类型转换周围的括号是必不可少的,因为 '.' 运算符的优先级高于类型转换。

于 2011-01-31T06:22:38.447 回答