Best practice for inner / anonymous classes

What is the best practice (design and performance) for anonymous classes and static inner classes?

Personally, I would like to think that static inner classes provide better encapsulation and should provide better performance because they do not have access to complete variables outside their class. But I never asked about that.

I found one message about this, but I felt that in fact he did not answer the question, but just people thought about it.

+6
source share
2 answers

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++; // Valid } } } 
  • Nested class (i.e. "static inner class")

     class A { private int field; private static class B { public void doSomething(A a) { a.field++; // Valid } } } 
  • Anonymous class

     class A { private int field; public void doSomething() { new Runnable() { @Override public void run() { field++; // Valid } } } } 

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.

+4
source

Look in the Java Collections and Pattern source code for a sample (they are in src.zip in the JDK directory. In Eclipse you can read the code using the built-in help

Read the book Effective Java , find the inner class to understand how static , inner and other useful interface , enum and other classes work.

+1
source

Source: https://habr.com/ru/post/926086/


All Articles