简体   繁体   中英

Why cast to Closeable first?

While reading some Java source, I came across this line:

((Closeable) some_obj).close();

some_obj is obviously an instance of a class which implements the Closeable interface. My question is, why do they first cast some_obj to Closeable before invoking close(). Couldn't I just do

some_obj.close();

Assuming the compile-time type of some_obj implements Closeable , then yes, you could.

You'd only need this if you had an object which you knew implemented Closeable , but where the compile-time type was something more general (the most obvious example being Object ) or otherwise "different" (eg a different interface).

Just as a matter of interest, in C# a cast to an interface type can make a difference, even if the compile-time type is known to implement the interface, due to explicit interface implementation. I can give more details if anyone cares, but I just thought I'd throw it out there.

如果变量some_obj已知编译时类型包含方法close()some_obj yes。

It sounds like typecast is unnecessary. (You could confirm this by trying to compile the class with the supposedly redundant typecast removed.)

We may never know why the code was written that way. It might be left over from a previous incarnation of the code where the declared type of some_obj was different. It might be that the developer had some stylistic issues ...

While it would (probably) the code's improve readability if the redundant cast was removed, it is not actually doing any harm. I expect that the Java compiler or the JIT compiler will optimize it away. And even if it doesn't, the cost of a redundant typecast is most likely insignificant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM