tags:

views:

55

answers:

2

Hi,

I am relatively a beginner in java and I am learning the google web toolkit (GWT). I saw this code snippet in their tutorial. I don't understand what is going on. I seems to be creating a ClickHandler Object in the constructor for a new Button object, and in the ClickHandler object we are overriding the onClick method? Is that what it is doing? Can we add more methods with this style, or just modify existing ones?

    package com.google.gwt.sample.hello.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Hello World application.
 */
public class Hello implements EntryPoint {

  public void onModuleLoad() {
    Button b = new Button("Click me", new ClickHandler() {
      public void onClick(ClickEvent event) {
        Window.alert("Hello, AJAX");
      }
    });

    RootPanel.get().add(b);
  }
}

Thanks

+5  A: 

This is what's known as an anonymous class. ClickHandler is an interface - to implement it, you need to define the onClick method. In this code sample, an anonymous subclass of ClickHandler is being created as a one-off and passed to the second argument of the Button constructor.

In response to the second part of your question, you could add more methods to the anonymous class if you wanted to, but there would be little reason as the Button class will not know to call any methods that are not defined by ClickHandler (and it would not be able to, because it only has a reference to the class as a ClickHandler).

Here is a link to more information on anonymous classes: http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm

danben
A: 

Following class is created on the fly (without any name) :

class AnnonymousClickHandler implements ClickHandler 
{ 
    public void onClick(ClickEvent event) {
         Window.alert("Hello, AJAX");
    } 
}

Name of the class is not AnnonymousClickHandler, I made up a name just to show an example.

fastcodejava