Java object literals?

I am learning GWT for web development and came across a piece of code that I cannot understand.

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

If someone can explain to me what he is doing, that would be great.

Thanks, John

+4
source share
4 answers

This is an anonymous inner class .

In this case, the code declares an unnamed class that implements the ClickHandler interface. When launched, an instance of the class will be created and passed to addClickHandler .

+11
source

I assume that the part you came across is an anonymous class. What happens here is that you call the addClickHandler method on the helloBtn object and pass it an instance of the anonymous class.

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

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

You can imagine rewriting code by first defining a class.

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

Then create an instance of the class and pass it to the addClickHandler method.

 ClickHandler myClickHandler = new MyClickHandler(); helloBtn.addClickHandler(myClickHandler); 
+3
source

This is an anonymous class - as the name says, a class without a name that can be defined "on the fly." In your sample code, it was used to implement the ClickHandler interface - Java is a somewhat verbose idiom for callbacks. The same syntax can be used to extend classes.

0
source

Another way to rewrite code without using an anonymous inner class is as follows:

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

Creates a ClickHandler object, which can then be passed where you need it:

 helloBtn.addClickHandler(myClickHandler); 

This style would be useful if you want to use the same ClickHandler for multiple elements so that it can look something like this:

 helloBtn1.addClickHandler(myClickHandler); helloBtn2.addClickHandler(myClickHandler); helloBtn3.addClickHandler(myClickHandler); 
0
source

Source: https://habr.com/ru/post/1303508/


All Articles