javaclassfieldlocal-class

Why can't create instance of local class in Java?


If I have this code.

public class Test{
        {
            class People {

            }
        }

        public static void main(String[] args) {
            People person = new People();//Compile ERROR
        }

    }

I can't create instance of People.

Does that mean Initializer Block can't be used for defining classes?


Solution

  • (Adding a second answer as my wrong one had three upvotes already.)

    You can declare a class within an initializer block - but its scope is that initializer block, just like if you declared it in a method. So this works:

    public class Test {
        {
            class People {            
            }
    
            People people = new People();
            System.out.println("In initializer block!");
        }
    
        public static void main(String[] args) {
            new Test();
        }
    }
    

    I can't say I've ever done this before though, nor can I imagine myself wanting to do it any time soon. Note that this is a local class, which is always implicitly an inner class. (Although if you declare a local class in a static method, there's no enclosing instance, just to make the terminology slightly weird...)

    If you want to create a class which code outside the initializer block can "see", you need to declare it outside the initializer block. (Just like any other declaration - if you declared a variable within the initializer block, you wouldn't expect to be able to see it outside would you?)