Vikram
Vikram

Reputation: 2069

Instance of abstract class InputStream

InputStream class defined as-

 public abstract class InputStream extends Object 

Then how System class can contain "in" object of InputStream class ?

Upvotes: 2

Views: 3865

Answers (3)

Andy
Andy

Reputation: 9058

The in field defined by the System class doesn't need to reference a concrete implementation of InputStream -- as you've worked out, it can't -- it just needs to reference something that extends InputStream.

On Linux at least, in references a BufferedInputStream that itself wraps a FileInputStream. Other implementations may vary and that's the point: the use of an abstract class like InputStream allows the implementing class to vary and potentially be changed from one version of Java to the next whilst keeping calling code happy.

Upvotes: 2

Bohemian
Bohemian

Reputation: 425198

An InputStream is the abstract, but the concrete class (the one actually referenced by System.in) can be any subclass of InputStream, including an anonymous class.

Some subclasses listed in the javadoc for InputStream include:

  • AudioInputStream
  • ByteArrayInputStream
  • FileInputStream
  • FilterInputStream
  • InputStream (CORBA)
  • ObjectInputStream
  • PipedInputStream
  • SequenceInputStream
  • StringBufferInputStream

Executing this code to find out which subclass System.in actual is:

System.out.println(System.in.getClass());

Yields this answer:

class java.io.BufferedInputStream

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533660

This is because in is not an object, its a reference.

Its a reference to an InputStream OR a sub-class of an InputStream. As its abstract, it can only be a sub-class.

Upvotes: 3

Related Questions