PS1 PS1 - 2 months ago 25
Java Question

Why cant a RandomAccessFile be casted to Inputstream?

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.

Answer

RandomAccessFile extends Object, and does not extend InputStream.

If you want get an InputStream from a RandomAccessFile I think implementing a wrapper class is your simplest bet. Luckily the only abstract method of InputStream is read().

RandomAccessFile implements DataInput which inturn DataInputstream & InputStream

DataInputStream is a subclass of InputStream, which also happens to implement DataInput. The inheritance and interface implementation tree looks like this:

           InputStream      DataInput
               \              /   \
                \            /     \
                 \          /       \
                DataInputStream   RandomAccessFile

You could use a DataInputStream anywhere where you could use an InputStream or a DataInput. You could use a RandomAccessFile anywhere where you could use a DataInput.

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 ClassCastException unless the object happens to be an instance of the child class.

Even though two classes happen to extend Object that doesn't mean they are interchangeable.

Comments