• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If abstract classes can't be instantiated, what is System.in?

 
Greg Stevens
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Miklos Szeles
Ranch Hand
Posts: 142
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ruben Guillen
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Greg

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.

Regards.
 
Greg Stevens
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47228
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.printf("System.in.getClass().getName() = %s%n", System.in.getClass().getName());
System.in.getClass().getName() = java.io.BufferedInputStream


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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic