posted 3 years ago
This is an "anonymous class declaration". The block is used to define the class body of an anonymous custom type that extends TreeMap. It's as if you had written the following code:
The important difference is that the class that you declare using an anonymous class declaration doesn't have a name, and a new instance of that class is created instantly.
Anonymous classes are used when you don't need to refer to the custom type outside of the method, and you only need one instance per method call. They're usually not used to extend complete classes like you did with TreeMap, but instead they are usually used to implement interfaces or abstract classes. The most common use case are event listeners:
Many interfaces have only one abstract method, and since Java 8 you can implement them using a lambda expression instead of an anonymous class declaration:
However, anonymous class declarations are still useful if an interface consists of more than one abstract method, or when you want to implement an abstract class, like I did above with MouseAdapter.
Some people abuse anonymous class declarations to add some initialization code to the new instance:
This syntax looks super weird, but it's really as if you wrote the following class:
Do NOT do this. It's poor, lazy programming. Instead, do this: