Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain Java Notation 'new' with bracketed code

Tags:

java

android

I see this notation, a new operator with a class name and then bracketed code, occasionally in Android examples. Can someone explain this? In the example below, PanChangeListener is a class (or maybe an interface) and 'new' creates an instance, but what role does the bracketed code 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, as I could Google it.

like image 787
Rdbhost Avatar asked Feb 21 '23 02:02

Rdbhost


2 Answers

That's an anonymous class.

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

When a local class is used only once, consider using anonymous class syntax, which places the definition and use of the class in exactly the same place.

It works in a similar way to the following code that doesn't use an anonymous class:

class MyPanChangeListener implements PanChangeListener()
{
    @Override
    public void onPan(GeoPoint old, GeoPoint current) {
        //TODO
    }
}

// ...

fType pcListener = new MyPanChangeListener();
like image 173
Mark Byers Avatar answered Mar 04 '23 08:03

Mark Byers


You are seeing the creation of an anonymous class here. It is creating either (a) an implementation of an interface named PanChangeListener or (b) a subclass of an abstract class of that name.

like image 25
bmargulies Avatar answered Mar 04 '23 09:03

bmargulies