Do anonymous classes *always* maintain a reference to their enclosing instance?

As of JDK 18, no. JDK 18 omits enclosing instance fields from inner classes that don’t use it. However, prior to JDK 18, yes, instances of anonymous inner classes hold on to a reference to their enclosing instances even if these references are never actually used. For example, this code: public class Outer { public … Read more

Automatic replacing all anonymous inner class to lambda in Intellij Idea

In the Analyze menu, select “Run Inspection by Name…”. In the search box, type “Anonymous” and select the one that says “Anonymous class may be replaced by lambda” or something to that effect. Select your scope and start the analysis. In the results, you can inspect them individually and click the “Replace with lambda” link … Read more

Why is an anonymous inner class containing nothing generated from this code?

I’m using polygenelubricants’s smaller snippet. Remember there’s no concept of nested classes in the bytecode; the bytecode is, however, aware of access modifiers. The problem the compiler is trying to circumvent here is that the method instantiate() needs to create a new instance of PrivateInnerClass. However, OuterClass does not have access to PrivateInnerClass‘s constructor (OuterClass$PrivateInnerClass … Read more

What’s the difference between anonymous classes in Java and closures?

There is almost no difference. In fact the there is an old saying about closures and objects. Closures are the poor man’s object, and objects are the poor man’s closure. Both are equally powerful in terms of what they can do. We are only arguing over expressiveness. In Java we are modeling closures with Anonymous … Read more

What’s the harm in using Anonymous class?

Except for the already mentioned issues regarding good programming style and inheritance misuse, there is one more subtle problem – inner classes and (non-static) anonymous class instances act as closures. This means that they keep an implicit reference to the enclosing class instance. This can result in preventing of garbage collection and in the end, … Read more

Is usage of anonymous classes in Java considered bad style or good? [closed]

I tend to use anonymous inner classes in situations where I don’t need to have a full-blown class just to perform some task. For example, if I want to implement an ActionListener or Runnable, but I don’t think having an inner class would be necessary. For example, for starting a simple Thread, using an anonymous … Read more