I get compilation error when I do this cast:
RandomAccessFile raf = new RandomAccessFile(...)
InputStream is = (InputStream)raf;
RandomAccessFile is supposed to subclass InputStream although not directly.
From docs:
RandomAccessFile implements DataInput which inturn DataInputstream & InputStream
Why is this invalid?
Also appreciate your input on what would be the right way to use the RandomAccessFile as InputStream?
I am thinking of wrapper approach.
RandomAccessFileextendsObject, and does not extendInputStream.If you want get an
InputStreamfrom aRandomAccessFileI think implementing a wrapper class is your simplest bet. Luckily the only abstract method ofInputStreamisread().DataInputStreamis a subclass ofInputStream, which also happens to implementDataInput. The inheritance and interface implementation tree looks like this:You could use a
DataInputStreamanywhere where you could use anInputStreamor aDataInput. You could use aRandomAccessFileanywhere where you could use aDataInput.But you can’t go up and then down in the inheritance hierarchy like this using casts. In particular, casting a class to a subclass (or an interface to an implementation) will raise a
ClassCastExceptionunless the object happens to be an instance of the child class.Even though two classes happen to extend
Objectthat doesn’t mean they are interchangeable.