I have written a simple code with a super class and two sub classes in order to track order or initialization. My static initializers behave like expected and initialize in the proper order. But my instance initializers seem to run twice before my constructors. I know that's the order of initialization but I'm trying to gain some insight an follow the flow and am lost as to why the instance initializers print twice. Here's my code and the output I receive. (see below)
class Bird{
static {System.out.println("Static Initializer 1");}
{System.out.println("Instance Initializer 1");}
int feathers = 0;
Bird(int x){ this.feathers = x; }
Bird fly() { return new Bird(1); }
}
class Parrot extends Bird {
static {System.out.println("Static Initializer 2");}
{System.out.println("Instance Initializer 2");}
protected Parrot(int y){ super(y); }
protected Parrot fly(){ return new Parrot(2); }
}
public class Macaw extends Parrot {
static {System.out.println("Static Initializer 3");}
{System.out.println("Instance Initializer 3");}
public Macaw(int z){ super(z); }
public Macaw fly(){ return new Macaw(3); }
public static void main(String... args){
Bird p = new Macaw(4);
System.out.println(((Parrot)p.fly()).feathers);
}
}
Results: