Java – why cast to closed first?
While reading some java source code, I came across this line:
((Closeable) some_obj).close();
some_ Obj is obviously an instance of a class that implements the closeable interface My question is, why do they call some first before calling close()_ Obj cast to closed I can't do that
some_obj.close();
Solution
Suppose some_ Obj's compile time type implements closeable, so yes, you can
If you have an object that you know is closeable, but the compile time type is more general (the most obvious example is object) or "different" (such as different interfaces), you only need this
It is also noteworthy that in C #, the explicit interface implementation will affect the cast of interface types even if the compile time type is known to implement the interface If someone cares, I can provide more details, but I just want to throw it out