Joker
Joker

Reputation: 11156

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.

Upvotes: 3

Views: 389

Answers (2)

davidxxx
davidxxx

Reputation: 131346

A nested class creates a distinct class.

Here you would have two classes :

  • AA.class

  • AA$BB.class

Using the second one doesn't require to load the first one as the second is a public static class.

Upvotes: 3

GhostCat
GhostCat

Reputation: 140457

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

Upvotes: 3

Related Questions