Home  >  Q&A  >  body text

Can an uninstantiated static object also call non-static methods in a class?

There is a very common code: System.out.println. This is a very common output statement, but after studying it for a while, I suddenly remembered to look at the source code. The following is the source code:

public final static PrintStream out = null;

out is defined under the System class and has not been instantiated. Out is just a null variable and cannot even be called a static object. However, it can call the println() method under the PrintStream class. This is not Too understanding? May I ask why?

为情所困为情所困2712 days ago633

reply all(5)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-17 10:09:52

    Detailed explanation: Chinese version http://www.cnblogs.com/skywan...
    English version based on jdk7 https://luckytoilet.wordpress...

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-17 10:09:52

    Dear, first of all, when you start your test class, that is, when you instantiate your test class, all the static classes you call will be instantiated first, so in fact, when you execute the System.out.println statement, The methods and properties in the System class have been initialized!

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-17 10:09:52

    static {

        registerNatives();

    }
    The annotation of the above static method says that the initializeSystemClass method will be called for initialization. The setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding"))); in this method should assign a value to out,
    private static native void setOut0(PrintStream out) is a native method;

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-17 10:09:52

    When I saw final static, my first reaction should be that this is a constant, and constants must be initialized. Then I looked for it again, and sure enough

    it calls a local method to initialize;

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-17 10:09:52

    Well, the initialization work done in the initializeSystemClass() function is called after the system thread is initialized. In other words, all static member variables (err out in) are initialized in this function.
    For example, this out:
    FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
    setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
    The setOut0() function is in the native layer , establish a connection between the initialized object and this out in the native layer

    reply
    0
  • Cancelreply