Witscale Test Center

4.6 Local inner class > 4.6.2 Instantiation


4.6.2 Instantiation


So far, we have only declared a method-local class but have not use it. Method-local class is useless unless it is instantiated and used. Its scope is only within a method. Therefore, it must be instantiated in a method, which declares it. Listing 4.5 shows how MyLocalInner is declared, instantiated and used.

 

The doSomething() method first defines the method-local class MyLocalInner and then it instantiates it. Note that the MyLocalInner instance can be created only after its declaration. More specifically, you can instantiate the class MyLocalInner anywhere below its definition within the method body of doSomething(). You cannot create MyLocalInner’s instance before its definition. Also, note that MyLocalInner is accessible only within the doSomething() method. Therefore, its instance can never be created outside the method body.