3

In my CS110 class, we are developing an Android application using the Google Maps API and one of the concepts being taught the Observer design pattern. The design pattern teaches the concept of a publisher and a subscriber. So when the state of the publisher changes, it notifies all the subscribers. In this example, the LocationListener is a subscriber but the implementation is confusing.

A snippet of the code looks as follows:

LocationListener locationListener = new LocationListener() {
  public void onLocationChanged(Location location) {
  // Called when a new location is found by the network location provider.
  makeUseOfNewLocation(location);
  }
  public void onStatusChanged(String provider, int status, Bundle extras) {}
  public void onProviderEnabled(String provider) {}
  public void onProviderDisabled(String provider) {}
};

LocationListener is an interface, and my understanding is you can't instantiate an interface. Yet, the LocationListener locationListener... statement is creating an object from an Interface, how is this possible?

Also, my understanding is this is an Anonymous class. I'm not quite sure I understand what it means for a class to be Anonymous. I understand what the word anonymous means, but not in the context of a class.

Any help in clarifying what is happening here would be greatly appreciated.

bitfactory
  • 33
  • 3

2 Answers2

2

Here's a link from the official Oracle Java site with a good explanation of "anonymous inner classes" which is what you are referring to: http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

Also, here is a good link to a similar question on stack overflow: How are Anonymous (inner) classes used in Java?

Community
  • 1
  • 1
ffhaddad
  • 1,653
  • 13
  • 16
1

LocationListener is an interface!

And locationListener is not an object but a reference of class LocationListener

In your code what you are doing is:

You are creating a reference of class LocationListener..If Class A implements interface B then reference of interface B can hold the object of class A..You are doing the same thing.

The Anonymous class is a class which does not have explicit declaration and definition. So in this part

new LocationListener() {
  public void onLocationChanged(Location location) {
  // Called when a new location is found by the network location provider.
  makeUseOfNewLocation(location);

you are defining an anonymous class which implements the interface LocationListener!

Hence the reference locationListener is holding the object of that anonymous class!

Hope this explains your question!!

Nullpointer
  • 1,086
  • 7
  • 20