1

There are many reasons to choose one design over another, and there are really good answers to it found in here:

I am curious if there are any performance or memory/storage difference when choosing static inner class via a regular class.

How does the difference looks like after compilation?

To be clear, This question is not about giving advice what to use in each case. I just want to learn how Java works here, behind the scene.

Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
  • 2
    There may be some minor differences, but performance is not the deciding factor on what to use. – Kayaman Oct 25 '19 at 13:40
  • 1
    @Kayaman this question is not about what to use. I just want to learn those minor differences to become more familiar with how Java works – Ilya Gazman Oct 25 '19 at 13:42
  • 1
    I just wanted to make sure that you're not choosing a design based on micro-performance. – Kayaman Oct 25 '19 at 13:44

1 Answers1

0

The static nested class is the simplest form: it works just like a top level class, the only difference is the scope in which it is declared. Nothing is hidden there.

The non-static nested class have a hidden reference to an instance of the enclosing class, that's why you can reference non-static fields of the enclosing class from inside the inner class.

When you define an anonymous class in a method, you will also have a copy of all the local variables declare in the method and referenced from within the anonymous class. If the method is non-static, you will also have the hidden reference to the enclosing class.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24