Tab Tab
Tab Tab

Reputation: 1

Wrapping byte array in ByteArrayInputStream

I am just trying to understand the wrapping of an array of bytes using ByteArrayInputStream class. Here is the code that I have doubt about it.

byte[] bytes = new byte[1024];

//write data into byte array...

InputStream input = new ByteArrayInputStream(bytes);

//read first byte
int data = input.read();
while(data != -1) {
    //do something with data

    //read next byte
    data = input.read();
}

My question is it it possible to write this part

InputStream input = new ByteArrayInputStream(bytes);

like this

ByteArrayInputStream input = new ByteArrayInputStream(bytes);

And why the author of this code created the object with both the super and sub classes?

I really thank you for your help.

Upvotes: 0

Views: 1959

Answers (2)

Hendrik
Hendrik

Reputation: 5310

Yes, you can write

InputStream input = new ByteArrayInputStream(bytes);

like

ByteArrayInputStream input = new ByteArrayInputStream(bytes);

It is functionally the same.

However, in OOP it's widely recommended to "program to interfaces". See What does it mean to "program to an interface"? for an explanation.

In this case, strictly speaking, InputStream is not an interface, but an abstract superclass. However, it more or less acts like an interface.

Upvotes: 2

user207421
user207421

Reputation: 310957

is it it possible to write this part

(InputStream input = new ByteArrayInputStream(bytes);)

like this

    ( ByteArrayInputStream input = new ByteArrayInputStream(bytes);)

Certainly. Why do you think otherwise? What happened when you tried it? Why are you using StackOverflow as a substitute for conclusive experiments?

And why the author of this code created the object with both the super and sub classes?

He didn't. He created the object as an instance of ByteArrayInputStream. He then assigned the result to a variable of type InputStream. It's perfectly normal.

Upvotes: 0

Related Questions