Question

Abstract class InputStream says that subclasses need to implement method read() which reads one byte and then turns it into an unsigned int.

System.in is an InputStream and I can do:

 int i = System.in.read();

My question is.. where is this method implemented? How come it works? Maybe an odd question but I'm trying to find out what's happening under the hood and since I'm using an object of class InputStream and not one of its subclasses, I'm wondering where the actual method is implemented and why it works...

Was it helpful?

Solution 2

InputStream is the type of System.in, and not it's class (since InputStream cannot be directly instantiated as it is abstract).

Consider:

Object obj = "123";

The type of the variable obj is Object, but the instance referenced by obj is an instance of String. When toString() is called on obj the implementation in String is used, and not the implementation in Object.

The same goes for System.in. The actual instance stored there will be some subclass of InputStream, which will have its own implementation of any abstract methods. If you want to know the class of the instance stored in System.in then you can call System.in.getClass().

OTHER TIPS

System.in is an implementation of an InputStream which has the read method implemented.

If you take a look in the source of System you can see it's really a FileInputStream opening the file handle 0 (which is the standard input stream). But this isn't really relevant. The only thing you need to know is that you can read from it. It isn't relevant if its a FileInputStream, a StringInputStream or some other native InputStream. That's the whole point of interfaces. You can mostly just program against an interface without worrying about the specific implementation.

What's happening under the hood is this: the in attribute of the class System is assigned, at runtime, a reference to an object of some class X. That class X extends InputStream, and as such, it implements the read method.

You can't tell for sure (meaning, it's not specified anywhere) what class X is; all you know is that it extends InputStream. Different JDK's might use different classes.

What is System.in.read() ?

1) System.in returns static InputStream in

First of all InputStream Class is an abstract class with its read method also abstract, this means there could be n number of implementations for the read method .

So whats happening behind the scenes ?

System.in returns an instance of InputStream class on runtime i.e class which extends InputStream as we know all byte stream classes extends InputStream , so it can be any class extending InputStream class. Now the read method is called from that class which it actually extending InputStream.

You can always check the instance provided for InputStream class by calling System.in.getClass()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top