Upcasting

上一篇 / 下一篇  2014-09-02 14:33:55 / 个人分类:Java

From http://stackoverflow.com/questions/5361999/whats-the-need-to-use-upcasting-in-java


In most situations, the upcast is entirely unnecessary and has no effect. However, there are situations where the presence of the upcast changes the meaning of the statement / expression.

One situation where it is necessary to use upcasting in Java is when you want to force a specific method override to be used; e.g. suppose that we have overloaded methods:

publicvoiddoIt(Objecto)...publicvoiddoIt(Strings)...

If I have a String and I want to call the first overload rather than the second, I have to do this:

Stringarg=...doIt((Object)arg);

A related case is:

doIt((Object)null);

where the code won't compile without the type cast. (I'm not sure if this counts as an upcast, but here it is anyway.)

A second situation involves varadic parameters:

publicvoiddoIt(Object...args)...Object[]foo=...doIt(foo);// passes foo as the argument arraydoIt((Object)foo);// passes new Object[]{foo} as the argument array.

A third situation is when performing operations on primitive numeric types; e.g.

inti1=...inti2=...longres=i1+i2;// 32 bit signed arithmetic ... might overflowlongres2=((long)i1)+i2;// 64 bit signed arithmetic ... won't overflow

TAG:

 

评分:0

我来说两句

Open Toolbar