views:

88

answers:

3

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();
+7  A: 

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.

Jon Skeet
technically, it might not be something "more general", just something "different" (a sibling type to Closeable).
Kevin Bourrillion
technically, technically, it might not be related to Closeable at all (in the non-cast version) ;-)
pst
+3  A: 

If the known compile-time type of the variable some_obj contains the method close(), then yes.

pst
+2  A: 

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.

Stephen C