46 lines
724 B
Plaintext
46 lines
724 B
Plaintext
== Why is this an issue?
|
|
|
|
Static field initializers are executed in the order in which they appear in the class from top to bottom. Thus, placing a static field in a class above the field or fields required for its initialization will yield unexpected results.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,text]
|
|
----
|
|
class MyClass
|
|
{
|
|
public static int X = Y; // Noncompliant; Y at this time is still assigned default(int), i.e. 0
|
|
public static int Y = 42;
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,text]
|
|
----
|
|
class MyClass
|
|
{
|
|
public static int Y = 42;
|
|
public static int X = Y;
|
|
}
|
|
----
|
|
|
|
or
|
|
|
|
|
|
[source,text]
|
|
----
|
|
class MyClass
|
|
{
|
|
public static int X;
|
|
public static int Y = 42;
|
|
|
|
static MyClass()
|
|
{
|
|
X = Y;
|
|
}
|
|
}
|
|
----
|
|
|