Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static nested class does not initialize outer class

When i initialize the static inner class i am expecting that outer class is also initialized and will print I should see this as well. however this is not happening and i am getting only class Main as a output

 class AA {
    static {
        System.out.println("I should see this as well.");
    }

    public static class BB {
        BB() {
            Object o = Main.class; 
            System.out.println(o.toString());
        }
    };
}

public class Test {
    public static void main(String[] args) {
        new AA.BB();
    }
}

Can some one help me , explaining this behavior.

like image 351
Sachin Sachdeva Avatar asked Mar 17 '26 13:03

Sachin Sachdeva


1 Answers

Thing is: that static initializer block gets executed lazily. Meaning: this code gets executed the first time that the AA class is really "required". But AA is not required to instantiate AA$BB.

If you change

BB() {
  Object o = Main.class; 
  System.out.println(o.toString());
}

to really require class AA to be loaded:

BB() {
  Object o = Main.class; 
  System.out.println(o.toString());
  new AA();
}

then that other string gets printed, too.

Keep in mind: it is only within your source code that BB is "inside" AA. From a class loader point of view, AA and BB are (somehow) two independent classes coming from two different class files!

Edit, given the question "how to see" that:

A) I replaced Main.class with Test.class and compiled, and I find in my file system AA$BB.class AA.class Test.class afterwards.

B) now you can run [javap][1] -c "AA$BB.class" to see more about the content of that class

like image 145
GhostCat Avatar answered Mar 19 '26 03:03

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!