According to the API, System field in is an InputStream. InputStream is an abstract class; its method read() is not defined. I thought that
abstract classes couldn't be instantiated. This confuses me. I understand that class System cannot be instantiated in a program, but, when
it is provided by the JVM or JRE, is System.in not somehow instantiated? Can someone please explain this apparent discrepancy to me?
You are right. Abstract classes can't be instantiated, but:
You can subclass an abstract class and you can implement the abstract methods. Whenever you see that some method returns an abstract class, it means that it returns an implementing subclass of that abstract class. Read this article. It explains a lot of thing.
In order to understand this concept, you need to refer yourself to the concept of polymorphism, static member variable "in" of class "System" is of Type "InputStream", and InputStream is an abstract Class. Now, variable "in" just hold a reference to an Object that can fullfill the requirement of "is a InputStream". That means that variable "in" can hold any instante of a concrete Class that extends InputStream as for example AudioInputStream, which fulfill the condition "is a InputStream". Concerning which specific instance is being assigned to variable in, is out of my knowledge probably somebody else could provide this information.
Joined: Jul 23, 2009
It makes sense that "in" points to an instance of some subclass of InputStream. Now this makes me want to ask
"what?" and "why?". I can't figure out what it is by looking at the API. And I wonder why the reference is of the superclass.
Oh, now I get it. It is of the superclass so that "in" can be changed with System method setIn.
Still curious to learn what it is initially though.
They do that sort of thing where there are several possible subclasses, which might vary from one implementation to another, and they think it is not necessary to know the difference in normal use. I have added a link so you can read more about the input stream.
subject: If abstract classes can't be instantiated, what is System.in?