Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Literals In Java?

Tags:

java

I am learning GWT for web development and came across a piece of code I can't really understand.

helloBtn.addClickHandler(new ClickHandler() {
    public void onClick(ClickEvent event) {
        Window.alert("Hello!");
    }
});

If someone could explain to me what it is doing that would be great.

Thanks, John

like image 313
John Jacquay Avatar asked Mar 08 '10 22:03

John Jacquay


2 Answers

This is an anonymous inner class.

In this case, the code is declaring an unnamed class which implements the ClickHandler interface. When run, an instance of the class will be created and passed to addClickHandler.

like image 179
Phil Ross Avatar answered Sep 22 '22 02:09

Phil Ross


I assume that the part you are having trouble with is the anonymous class. What is happening here is that you are calling the addClickHandler method on the helloBtn object and passing it an anonymous class instance.

The addClickHandler method takes an instance of the ClickHandler as an argument. The following code is creating the anonymous class that implements the ClickHandler interface.

new ClickHandler() {
public void onClick(ClickEvent event) {
    Window.alert("Hello!");
}

You could imagine rewriting the code by first defining the class.

public class MyClickHandler implements ClickHandler {
  public void onClick(ClickEvent event) {
    Window.alert("Hello!");
  }
}

Then creating an instance of the class and passing it to the addClickHandler method.

ClickHandler myClickHandler = new MyClickHandler();
helloBtn.addClickHandler(myClickHandler);
like image 38
Randy Simon Avatar answered Sep 19 '22 02:09

Randy Simon