Question

I am just a newbie in Java. I was wondering the way System.out.println() is used. Out is a static field inside System class. The type of out is PrintStream. But when I saw the constructor of PrintStream class, it takes a parameter of type OutputStream and as far as I know we cannot create the object of an abstract class. In that case we must pass some subclass's object to the constructor of PrintStream. What is that class? Same is the System.in. It is also InputStream's reference but what is the type of object it points to as the InputStream is abstract?

Was it helpful?

Solution

PrintStream wraps BufferedOutputStream, which wraps FileOutputStream, which is writing into the console, which has its own FileDescriptor.

OTHER TIPS

A simple way to view the structure of a class is to examine it in a debugger.

As you can see @Andremonify's description is basically what you have.

FileDescriptor

  • 0 is System.in
  • 1 is System.out
  • 2 is System.err
  • 3+ is used for other files

enter image description here

Yes out is of PrintStream type. And constructor of PrintStream takes OutputStream type. OutputStream is abstract class. But any superclass refrence can refer subclass object without casting, so PrintStream's constructor has OutputStream refrence, but this refrence must be referring one of OutputStream's subclass like FileOutputStream

There are a couple more things to say about the implementation of System.out.

  1. The actual implementation class of System.out is not specified. The javadocs don't say what it is. We observe (in various way) that Oracle Java and OpenJDK Java implement the "stack" in a particular way (see other answers), but this could change in the future.

  2. The System::setOut(PrintStream) method can be used to modify what System.out is bound to. If that happens, any assumptions about implementation classes may be incorrect.

  3. It turns out that you can do this:

      System.setOut(null);
    

    so System.out could be null. However, with current implementations, System.out won't be null unless you set it to null.

All that is actually guaranteed by the specifications is that the value of System.out will have a type that is assignment compatible with PrintStream.

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