It seems the main confusion is just due to not understanding the various blocks that a class can have;
this answer gives a nice example and explanation;
Here's the code they give:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized).
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs before the constructor each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
This class has a static initialiser
, an instance initialisation block
, a constructor
, and a class method
.
static initialiser
: static {...}
instance initialiser
: {...}
constructor
: Public ClassName(){...}
class method
: Public Static Whatever classMethod(String[] args){...}
Each of these is called under different circumstances; the static initialiser
is called when the class is loaded, there's no other way to call it, you can't even do it via reflection, as it's never represented by a method instance
, it is called by the JVM.
the instance initialiser
is called whenever you create an instance of the class - before the constructor.
You can have multiple static initialiser
s, and multiple instance initialiser
s, and they are executed in the order they appear in the code.
constructor
and class method
you presumably already know about.
In your example, it would probably be a little more helpful to rearrange the code slightly, to better reflect that hierarchy;
public class goFuncTest {
//static instance initialiser
static {
System.out.print("4 ");
}
//instance initialiser
{
System.out.print("2 ");
}
//Constructor
goFuncTest(){
System.out.print("1 ");
}
//Class method
void go(){
System.out.print("3 ");
}
public static void main(String[] args){
new goFuncTest().go();
}
}
(editted to add in the static keyword)