0

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.

Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118
Tab Tab
  • 1
  • 3
  • `InputStream input` is not an object, it is a reference to an object which must implement this interface. Note: you can't create an instance of InputStream. – Peter Lawrey Dec 28 '14 at 10:12

2 Answers2

2

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.

Community
  • 1
  • 1
Hendrik
  • 5,085
  • 24
  • 56
0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thank you for the answers, I was not experimenting here. I'm looking for help to understand the concept. I think that is the purpose of the site right? – Tab Tab Dec 28 '14 at 10:07
  • @TabTab What is often baffling for experienced developers is why people ask questions which is surely easier to work out for yourself. – Peter Lawrey Dec 28 '14 at 10:11