简体   繁体   English

Java,已实现接口的传递对象

[英]Java, passing object of implemented interface

Below code snippet is from the website of smartgwt. 下面的代码段来自smartgwt的网站。 While calling the method addButtonClickHandler implementation of the interface ButtonClickHandler is passed as anonymous object.What is this concept called in Java? 在调用接口ButtonClickHandler的addButtonClickHandler实现方法时,它作为匿名对象传递。在Java中,这个概念叫什么?

    final Dialog dialog = new Dialog();
      dialog.setMessage("Please choose whether to proceed");
      dialog.setIcon("[SKIN]ask.png");
      dialog.setButtons(new Button("OK"), new Button("Cancel"));
      dialog.addButtonClickHandler(new ButtonClickHandler() {
          public void onButtonClick(ButtonClickEvent event) {
              dialog.hide();
          }
      });
     dialog.draw();    

ButtonClickHandler is an interface with onButtonClick as a only method. ButtonClickHandler是一个接口,其中onButtonClick是唯一方法。

This concept is called Anonymous Inner Classes - An inner class without specifying a name 此概念称为Anonymous Inner Classes - 不指定名称的内部类

Anonymous classes enable you to make your code more concise. 匿名类使您可以使代码更简洁。 They enable you to declare and instantiate a class at the same time. 它们使您可以同时声明和实例化一个类。 They are like local classes except that they do not have a name 它们就像本地类,只是它们没有名称

This is more often used in Writing Event Listeners such as Swing, GWT etc. 这在编写事件侦听器 (如Swing,GWT等)中更常用。

Anonymous classes are often used in graphical user interface (GUI) applications. 匿名类通常在图形用户界面(GUI)应用程序中使用。

Examples of Anonymous Classes 匿名类的例子

Anonymous class 匿名班
You don't have to create class that implements interface that is required as an argument in separate file and then initialize it and pass it. 您不必创建实现作为单独文件中的参数所必需的接口的类,然后对其进行初始化并传递它。 You can do it in same line where it's needed. 您可以根据需要在同一行中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM