What is the type of System.out in Java?

让人想犯罪 __ 提交于 2019-12-04 09:15:02

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!