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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With