-1

I came across a problem while experimenting with subclasses and constractors and if possible i would like someone to explain it to me.

class AA {
    AA(){System.out.println("AA");}
}

class BB {
    BB() { System.out.println("BB");}
    BB(int k) { System.out.println("BB"+k);}
}

class CC extends BB {
    CC() { System.out.println("CC"); }
    CC(int k) {
        super(k);
        for (int j=0;j<5;j++) {
            System.out.print("o");
        }
    System.out.println(k);
    }
}

class DD extends CC {
    AA a3 = new AA();
    DD(int k) { super(k);}
    DD() {
        this(2);
        System.out.println("CC");
    }
}

class Program {
    public static void main(String[] a) {
        DD d = new DD();
    }
}

This prints

BB2
ooooo2
AA
CC

but i can't really undertstand why. After this(2) is called, shouldn't the program move forward to System.out.println("CC") and then create the instance of class AA? Seems like after it entered the DD() constractor, it executed half of it, then created a3 and then came back to continue the constractor execution.

(i was expecting:)

BB2
ooooo2
CC
AA  

Thanks in advance for your help.

  • See [this](https://stackoverflow.com/questions/23093470/java-order-of-initialization-and-instantiation) question, especially paragraphs 4-5 of meriton's answer. – John McClane Nov 23 '18 at 21:13

1 Answers1

0

Java does not compile the assignments of the initial values of fields as you seem to think. You're probably think that the initial value gets assigned to fields after the constructor call is done, but that's not the case. It is actually done after any super(); call.

So here's an example:

class Foo {
    String string = "Hello";

    Foo() {
        System.out.println("Hello World");
    }
}

This is what it would compile to:

class Foo {
    String string;

    Foo() {
        // First the constructor of the superclass must be called.
        // If you didn't call it explicitly, the compiler inserts it for you.
        super();

        // The next step is to assign the initial values to all fields.
        string = "Hello";

        // Then follows the user written code.
        System.out.println("Hello World");
    }
}
Aki
  • 1,644
  • 12
  • 24