Bartzilla
Bartzilla

Reputation: 2794

Why in GWT an interface is instantiated?

Going through this tutorial https://developers.google.com/web-toolkit/doc/latest/tutorial/RPC it is mentioned that to set up a call back Object it is necessary to do the following:

// Set up the callback object.
AsyncCallback<StockPrice[]> callback = new AsyncCallback<StockPrice[]>() {
  public void onFailure(Throwable caught) {
    // TODO: Do something with errors.
  }

  public void onSuccess(StockPrice[] result) {
    updateTable(result);
  }
};

However I noticed AsyncCallback is an interface. As far as I knew interfaces could not be instantiated. How is this possible?

Upvotes: 0

Views: 115

Answers (2)

Travis Webb
Travis Webb

Reputation: 15018

This is an example of using an Anonymous Class to implement a callback in Java. This is equivalent to defining a class that implements that interface. To clarify, this:

new AsyncCallback() {
    ...
}

is equivalent to this:

public class MyCallback implements AsyncCallback {
    ...
}

In fact, if you wanted to, you could create your own class in a separate Java file, call it MyCallback, and then do this:

AsyncCallback<StockPrice[]> callback = new MyCallback();

It's all the same.

Upvotes: 4

01es
01es

Reputation: 5410

This is the case of anonymous inner class implementation of that interface.

The demonstrated approach is very frequently used for implementing different listeners and callbacks. More on the topic can be found here.

Upvotes: 1

Related Questions