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
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With