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?
PrintStream
wraps BufferedOutputStream
, which wraps FileOutputStream
, which is writing into the console, which has its own FileDescriptor
.
FileDescriptor
. The File
class is not used. –
Seagraves 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
FileInputStream
for stdin
, FileOutputStream
for stdout
. What about stderr
–
Insouciance PrintStream
wraps BufferedOutputStream
, which wraps FileOutputStream
, which is writing into the console, which has its own FileDescriptor
.
FileDescriptor
. The File
class is not used. –
Seagraves 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
.
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.The
System::setOut(PrintStream)
method can be used to modify whatSystem.out
is bound to. If that happens, any assumptions about implementation classes may be incorrect.It turns out that you can do this:
System.setOut(null);
so
System.out
could benull
. However, with current implementations,System.out
won't benull
unless you set it tonull
.
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
.
null
does not have an implementation class. Which is why "assignment compatible" is technically more accurate than what you said.) –
Silk © 2022 - 2024 — McMap. All rights reserved.
System.out.println(System.out.getClass());
or view it in your debugger. ;) – Seagravesclass java.io.PrintStream
nothing else :) The idea with debugger is more efficient ;) – Gymnasiarch