Can an uninstantiated static object also call non-static methods in a class?
为情所困
为情所困 2017-05-17 10:07:52
0
5
682

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?

为情所困
为情所困

reply all(5)
我想大声告诉你

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

滿天的星座

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!

仅有的幸福

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;

Peter_Zhu

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;

给我你的怀抱

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template