I have gone through some related topics on internet like this and questions here like this, this and this, but I'm getting nowhere. Here is my simplified code:
MainActivity:
package com.test.staticvariables;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Test1 test1 = Test1.getInstance();
// do something
Test2.printTest1Instances();
}
}
Test1:
package com.test.staticvariables;
public class Test1 {
private static Test1 test1;
static {
System.out.println("Initializing Test1, loader: " + " " + Test1.class.getClassLoader());
}
static synchronized Test1 getInstance() {
if (test1 == null) {
test1 = new Test1();
}
return test1;
}
private Test1() {}
}
Test2:
package com.test.staticvariables;
public class Test2 {
private static final Test1 test1;
// private static final Test1 test1 = Test1.getInstance();
// private static final Test1 test1 = getTest1Instance();
static {
System.out.println("Initializing Test2, loader: " + " " + Test2.class.getClassLoader());
test1 = Test1.getInstance();
}
static Test1 getTest1Instance() {
return Test1.getInstance();
}
private Test2() {}
static void printTest1Instances() {
System.out.println("Test1 class variable: " + test1);
System.out.println("Test1 instance variable: " + Test1.getInstance());
}
}
Result:
Initializing Test1, loader: dalvik.system.PathClassLoader[DexPathList...]
Initializing Test2, loader: dalvik.system.PathClassLoader[DexPathList...]
Test1 class variable: com.test.staticvariables.Test1@2a7bfa4
Test1 instance variable: com.test.staticvariables.Test1@7e2a464
Why are two instances created of class Test1
(2a7bfa4
and 7e2a464
)?
Please note that Test2
only contains static methods, it's not being instantiated.
The app runs in a single native process, so the classes should be loaded by the same class loader (if I understand it correctly).
Declaring and initializing (inside or outside a static method or a static initialization block) a final static variable holding other class instance is a wrong / bad practice? Or is it wrong under certain situations?