Explain Java Notation β€œnew” with square brackets

I see this notation, a new statement with the class name, and then the code enclosed in brackets, sometimes in Android examples. Can someone explain this? In the example below, the PanChangeListener is a class (or possibly an interface) and the β€œnew” creates an instance, but what role does the code in square brackets play with respect to the PanChangeListener?

fType pcListener = new PanChangeListener() { @Override public void onPan(GeoPoint old, GeoPoint current) { //TODO } }); 

Even a name for this syntax would be useful since I could use it by Google.

+4
source share
2 answers

This is an anonymous class.

The syntax allows you to create a new class, provide an implementation for some methods, and then instantiate it.

If the local class is used only once, consider using the syntax of an anonymous class, which puts the definition and use of the class in exactly the same place.

It works similarly to the following code, which does not use an anonymous class:

 class MyPanChangeListener implements PanChangeListener() { @Override public void onPan(GeoPoint old, GeoPoint current) { //TODO } } // ... fType pcListener = new MyPanChangeListener(); 
+7
source

Here you see the creation of an anonymous class. It creates either (a) an implementation of an interface named PanChangeListener , or (b) a subclass of the abstract class of that name.

+1
source

All Articles