1

I am preparing for OCJA exam where I came across the concept of static blocks. I was trying the different combination where I have noted that nesting of instance blocks are allowed but nesting of static blocks are not allowed. Why nesting of static blocks are not allowed? Unfortunately I am not able to find the online resource where this reason can be explained.

Below is nesting of instance block which compiles fine.

  class Test {
   { 
        {
            System.out.print("Instance Block One");
            {
                System.out.print("Nested Instance Block");
            }   
        }   
    }

      public static void main(String[] args){
        System.out.print("Main Method");    
     }
}

Below is nesting of static block which fails at compile time.

  class Test {
    static{ 
            static{
                System.out.print("Static Block One");
                    static{
                        System.out.print("Nested static Block");
                    }       
                }   
        }

   public static void main(String[] args){
      System.out.print("Main Method");  
   }
}
Gaurav Pathak
  • 2,576
  • 1
  • 10
  • 20
  • 1
    Both, nesting of instance and static blocks, does not make sense - and both is not allowed. Yet your first example does work, but it is not nesting instance blocks, but nesting block statements (which are syntactically equal to an instance block) in the instance block. You may also nest block statements in static blocks. – CoronA Dec 02 '17 at 14:59
  • @CoronA As mentioned by you I have tried the block statement inside the static block and it have compiled fine for me. I agree that it does not make any sense by nesting of static blocks. – Gaurav Pathak Dec 02 '17 at 15:07

0 Answers0