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 j开发者_Python百科ust 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" (e.g. 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.
If the known compile-time type of the variable some_obj
contains the method close()
, then 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.
精彩评论