Inner classes (static or not) have exactly the same access to the fields and classes of the enclosing class as anonymous classes, the difference between static inner classes (actually called nested classes) and (regular, non-static) inner classes that static requires an explicit reference to the surrounding instance class for access to anything. Of course, when you need it, it is usually an instance of the class that creates the inner class, so itโs easier and more understandable to use a non-static inner class.
Examples:
Inner class (non-static)
class A { private int field; private class B { public void doSomething() { field++;
Nested class (i.e. "static inner class")
class A { private int field; private static class B { public void doSomething(A a) { a.field++;
Anonymous class
class A { private int field; public void doSomething() { new Runnable() { @Override public void run() { field++;
If you use this availability, this is another question. If you access private fields of the surrounding class, an accessor will be created, so it can affect performance, since the cost of calling the method does not coincide with access to the field, but in most cases this will be insignificant, you should always write the correct code first (as with design point of view, as well as with functionality) before performing microoptimization, not based on any measurements. In any case, the JIT compiler does a lot for you.
source share