Reputation: 71
public class InstanceBuilder {
private static final InstanceBuilder INSTANCE = new InstanceBuilder();
private static String name = null;
private InstanceBuilder() {
System.out.println("Setting cons()");
name = "Testing";
}
public static String getName() {
return name;
}
}
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("value is " + InstanceBuilder.getName());
}
}
Output:
Setting cons()
value is null
Why does it print value as null
even though I have set the static
variable in constructor and it is called as expected. If I try to print in constructor, it is printing Testing
, but if I call from public static
method, it is null
. I know if I change it to INSTANCE.name
, it works.
But I want to understand why it is not working if I directly access static
variable since same copy should be shared.
What I am missing here?
Upvotes: 5
Views: 3000
Reputation: 3724
Because the value of name is getting modified after the constructor invocation as per the declaration order.
Lets see what is happening:
1) When you call InstanceBuilder.getName()
, InstanceBuilder
class is getting loaded. As part of that process INSTANCE
and name
instance variables are getting initialized.
2) While initializing INSTANCE
,
private static final InstanceBuilder INSTANCE = new InstanceBuilder();
constructor of InstanceBuilder
class is getting invoked & Setting cons()
statement is getting printed and name
variable is initialized with Testing
.
3) Next name
is again getting re-initialized with null
due to the below statement
private static String name = null
;
so when the method call returns to Driver
class, value of name
is null
and null
is getting printed. So even though name
is declared as static
, static has no role in that context.
Note:
Check the below link on the order of which class members should be declared
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#1852
Upvotes: 8
Reputation: 3507
Here value is null because static initialization occurs as its declare in order, So First your
`private static final InstanceBuilder INSTANCE = new InstanceBuilder();`
code execute and assign value to "testing", then your
`private static String name = null;`
code exceute and override value to null(as static variable have coppy per class only), so final value will be null.
So here this behavior is just beacuse of order of execution of static variable
Upvotes: 0