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…
InputStreamis the type ofSystem.in, and not it’s class (sinceInputStreamcannot be directly instantiated as it is abstract).Consider:
The type of the variable
objisObject, but the instance referenced byobjis an instance ofString. WhentoString()is called onobjthe implementation inStringis used, and not the implementation inObject.The same goes for
System.in. The actual instance stored there will be some subclass ofInputStream, which will have its own implementation of any abstract methods. If you want to know the class of the instance stored inSystem.inthen you can callSystem.in.getClass().