Mob
Mob

Reputation: 11106

Static initialization block skips

The static initialization block in the non-public class Out doesn't run, yet the static initialization block in the static nested class snOut runs. How and why is this possible?

public class staticNested {

    static{
        System.out.println("In staticNested");
    }

    static class sn{

        static{
            System.out.println("sn in staticNested");
        }

        void p(){
            System.out.println("In static nested class method p");
        }
    }

    public static void main(String [] args){
        sn n = new sn();
        n.p();

        Out.snOut no = new Out.snOut();
        no.p();
    }
}

 class Out{

     static{
         System.out.println("In Out"); //Skips this
         System.out.println("Here");  //Skips this
     }

     static class snOut{

         static {
             System.out.println("In snOut in Out");
         }

            private int x;

            void p(){
                System.out.println("In snOut in outside Class out: " + x);
            }

        }
    }

This is the output:

In staticNested
sn in staticNested
In static nested class method p
In snOut in Out
In snOut in outside Class out: 0

Upvotes: 2

Views: 168

Answers (3)

Andremoniy
Andremoniy

Reputation: 34920

Actually in your code you did not use the class Out by it self. This is the cause, why Java didn't initialize it and didn't call its static section.

UPD.: Explanation. Your code leads to the initialization of the class Out.snOut, but this is not a cause for the initialization of the class Out.

Upvotes: 1

kosa
kosa

Reputation: 66677

As per JLS 8.1.3

An instance of an inner class I whose declaration occurs in a static context has no lexically enclosing instances.

In your code you are trying to access class sn which is static, so it will not have any enclosing classes as per specification. That is why static block of enclosing classes are not executing.

Upvotes: 3

Subin Sebastian
Subin Sebastian

Reputation: 10997

Your inner classes are static. This means they are just like outer classes, and an object of their type can initialize without the need of parent object. So here parent objects are never initialized and their static initializing blocks not executed.

Upvotes: 1

Related Questions