How to reference local class

788 Views Asked by At

I have a local class...

public class Outer {
    public void wrapper() {
        class Local {
        }
    }
}

and I have a test that needs to reference the local class...

Outer.wrapper.Local.class ## this doesn't seem to work

How can I reference the local class?

2

There are 2 best solutions below

5
Karol Dowbecki On BEST ANSWER

You can only reference a Local Inner class inside the method in which you have declared it:

public void wrapper() {
  class Local {

  }
  Local obj = new Local();
}

This classes tend to not be very useful due to their limited scope. If you have found a valid use case to define one take a look at this tutorial.

5
prasad_ On

Local Class (a.k.a. Local Inner Class or Method-Local Inner Class):

Local class is defined as an inner class within a method. Like local variables, a local inner class declaration does not exist until the method is invoked, and it goes out of scope when the method returns. This means its instance can be created only from within the method it is declared in.

This inner class can be instantiated only after its definition (i.e., the instantiation code must follow the declaration). The inner class do not have access to local variables of the method unless those variables are final or effectively final.

Here is an example:

int length = 10; // outer class's instance variable

public void calculate() {
    final int width = 20;
    class Inner { // inner class definition
        public void area() {
            System.out.println(length * width);
        }
    }
    Inner local = new Inner(); // this statement comes only after local class's definition
    local.area();
}

NOTES:

  • The only modifiers that can be applied to a method-local inner class are abstract and final, but never both at the same time.
  • A local class declared within a static method has access to only static members of the enclosing class, and no access to instance variables.