Passing ByteArrayOutputStream into the Constructor of DataOutputStream

I understand that this can be done using wrapper pattern, but i am having a hard time understanding, how does the following code work.

ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
DataOutputStream os = new DataOutputStream(bytearray);

passing ByteArrayOutputStream reference into the constructor of DataOutputStream means that the DataOutputStream gets converted to ByteArrayOutputStream, but how?

After this, os.writeUTF("String"); How does DataOutputStream convert to ByteArrayOutputStream.

What is happening behind the scenes? Can somebody please explain the details.

Answers


The DataOutputStream only requires any implementation of an OutputStream in its constructor. It doesn't care how it's implemented only that it satisfies the interface. A ByteArrayOutputStream provides an output stream backed by a byte array. Similarly, you could use a FileOutputStream to get a stream backed by a file on disk. From the DataOutputStream's perspective, they are both streams that used with an interface. OutputStream is a really simple interface, and just defines some methods that write byte arrays to some kind of storage device.

There's no magic going on under the scenes, it just uses an OutputStream and doesn't care how it's implemented.


Need Your Help

Yii SQLSTATE: Invalid parameter number: parameter was not defined

php pdo yii

I have looked at the other questions concerning this error message, but all appear to have something to do with a miss match between a parameter and its binding, or missing bindings, or something l...

Count frequency of letters in a text file

python text

In python, how can I iterate through a text file and count the number of occurrences of each letter? I realise I could just use a 'for x in file' statement to go through it and then set up 26 or so...