How does this code compile, although we use a constant that is defined later?

In the following code, DEFAULT_CACHE_SIZE is declared later, but it is used to assign the value of the String variable before that, so I was curious how this is possible?

public class Test { public String getName() { return this.name; } public int getCacheSize() { return this.cacheSize; } public synchronized void setCacheSize(int size) { this.cacheSize = size; System.out.println("Cache size now " + this.cacheSize); } private final String name = "Reginald"; private int cacheSize = DEFAULT_CACHE_SIZE; private static final int DEFAULT_CACHE_SIZE = 200; } 
+4
source share
3 answers

From Sun docs :

A static modifier in combination with the last modifier is also used to define constants. The last modifier indicates that the value of this field cannot change.

If a primitive type or string is defined as a constant, and the value is known at compile time, the compiler replaces the name of the constant everywhere in the code with its value. This is called a constant compilation constant.

There is a compile time constant in your DEFAULT_CACHE_SIZE code.

+8
source

The static properties of a class are always resolved immediately after loading the class, which is obviously what happens before the class is instantiated by the object.

Unlike, for example, C ++, where everything must be declared in the source before use, in Java the actual order of constructors, fields, and methods does not affect the evaluation order and time of various class properties.

+4
source

It is not used before, it is defined. The destination may be on the line above in the source, but it doesn’t matter - javac reads the entire source file and then starts generating the code. (The way he can define things like "a personal variable is never used", etc.). In other words, the order of the statements is important to determine which operators in the sequence are executed first, but the neighboring elements of the class do not have an β€œorder” of this kind among them.

However, there are rules for static / non-static elements, and they guarantee that this value will be available after loading the classes and before creating the object.

0
source

Source: https://habr.com/ru/post/1304699/


All Articles