3

It's been a few years since I've been heavily into Java. Coming back to it I'm seeing this pattern all over the place:

ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
  public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
    // do work
  }
});

This looks more like Functional programming to me. It's a nice pattern but how is it possible to pass a method like this? In the old days a class was a class, and once compiled there was little you could do to it.

My questions are:

  1. Can anyone let me know what this pattern is called?
  2. How can I write a class that can be instantiated in this way.
  3. Are there any other useful examples of functional patterns that have made their way into Java?
  4. What do I need to Google to read more about this?

Thanks.

4 Answers 4

9

This passes an anonymous class, not a method.

This is a typical pattern, not just in Swing programming, but anywhere you need (hopefully) short, "throw-away" implementations of an interface or class that doesn't need to be re-used, instead of creating a full-blown implementation.

Any class/interface can be instantiated like this, there's nothing special about it:

public interface Foo {
    String foo();
}

...

public class Main {
    public static void main(String[] args) {
        System.out.println(new Foo() {
            public String foo() {
                return "plugh";
            }
        });
    }
}

Anonymous inner classes get their own class files, too, even though their source is embedded.

In this example, a Main$1.class file will be generated for the anonymous inner class, in addition to the expected Main.class file.

Sign up to request clarification or add additional context in comments.

5 Comments

An "anonymous inner class", to be pedantic :-) For the OP, these have been part of Java from the very beginning.
Ah, and onRatingChanged is a static method. Thanks for your help, I feel rather foolish now :)
@superluminary No, it's not a static method--if it was, it would have a static keyword. Plus static methods aren't overridable, just hidable.
Sorry, I meant to say abstract.
@superluminary It may be, but it doesn't have to be. In this case, assuming this is Anroid code, it's an implementation of an interface's abstract method. (Although "abstract" in an interface seems weird to me.)
1

The statement: new OnRatingBarChangeListener() creates a new instance of a class. The following part inside the curly braces is the definition of the class.

In this case that class in an anonymous class that implements the named interface.

Anonymous classes are classes, that are declared without a name, and thus, can not be used like regular named classes.

This pattern is very common when using listeners, that often contain only a single to a few methods that do an almost trivial task.

Comments

0

This is the Listener pattern. Rating bar takes an implementation of OnRatingBarChangeListener and calls its onRatingChanged method on the appropriate event.

You can use instance of any class which implements OnRatingBarChangeListener. So you can use either a named class of your own or you can pass it an anonymous class like in the example. The anonymous class in the example is effectively a unnamed class which extends Object and implements OnRatingBarChangeListener. Since the class isn't named it cannot be referenced and so the instance passed is the only instance existing.

Comments

0

This is called "Observer pattern". A good example for this is adding action listeners for java button or other component. For example,

myButton.addActionListener(
                new java.awt.event.ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    //Work here
                }
            });

In here "myButton" is the subject and ActionListener is the observer.

1 Comment

IMO by not discussing the root nature of what's happening this at least somewhat misses the OP's point--showing an essentially-identical example doesn't really help explain anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.