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_objimplementsCloseable, 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 beingObject) 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.