javainputstreamsystem.in

Java: Where is InputStream's read() method implemented when reading from System.in


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...


Solution

  • 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().