开发者

How this is code is getting compiled even though we are using a constant which is defined later?

开发者 https://www.devze.com 2022-12-23 10:25 出处:网络
In the following code DEFAULT_C开发者_如何学JAVAACHE_SIZE is declared later, but it is used to assign a value to String variable before than that, so was curious how is it possible?

In the following code DEFAULT_C开发者_如何学JAVAACHE_SIZE is declared later, but it is used to assign a value to String variable before than that, so was curious how is it 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; 
}


From Sun docs:

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

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

In your code DEFAULT_CACHE_SIZE is a compile-time constant.


Static properties of the class are always resolved immediately after the class is loaded which is obviously something that happens before the class is instantiated to an object.

Unlike in for example C++ where everything must be declared in source before usage, in Java the actual order of constructors, fields and methods have no effect on the evaluation order and time of the various properties of the class.


It's not used 'before' it is defined. The assignment may be on a line higher up in the source, but that is irrelevant - javac reads the entire source file and then starts generating code. (That's how it is able to determine things like 'private variable never used' etc.) In other words, order of statements matters to determine which statements in a sequence gets executed first, but neighbour elements of a class do not have an 'order' of this kind among them.

However, there are rules about static/nonstatic elements, and these guarantee that the value will be available after class loading and before object instantiation.

0

精彩评论

暂无评论...
验证码 换一张
取 消