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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With