-1

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:

results

Slaw
  • 37,820
  • 8
  • 53
  • 80
JBee
  • 1
  • 1
  • 1
    Because you have two classes. In the static case, both `Bird` and `Parrot` classes need to be initialized. In the instance case, both `Parrot` and `Bird` instance initialization is run ... because a `Parrot` is a `Bird`. This is the way that initialization works in Java ... – Stephen C Nov 19 '21 at 05:16
  • 3
    You call `fly()`, which creates another `Macaw` instance. So you have two instances of `Macaw` being instantiated in your program. – Slaw Nov 19 '21 at 05:19

1 Answers1

4

Probably because your fly() method literally creates a new instance:

public Macaw(int z){ super(z); }
    public Macaw fly(){ return new Macaw(3); } <---- NEW

    public static void main(String... args){

        Bird p = new Macaw(4); // Instance 1
        System.out.println(((Parrot)p.fly()).feathers); // Calling fly() creates instance 2
    }
dominicoder
  • 9,338
  • 1
  • 26
  • 32
  • That makes absolute sense. Just to hear myself verbalize it, even if the objects/classes are created, every new instance gets initialized again as if it's the first time being initialized. Hence the keyword New. Thanks again. – JBee Nov 19 '21 at 06:26
  • 1
    Just to clarify: `every new instance gets initialized again as if it's the first time being initialized.` - > every new instance gets initialized ~again as if~ _because_ it's the first time being initialized. When you call `fly()` on `p`, it's not that `p` is getting initialized _again_ - it's that a new instance of type `Macaw` is being created and initialized for the first time. – dominicoder Nov 19 '21 at 06:38