繁体   English   中英

如何使用匿名内部类?

[英]How to use the anonymous inner class?

我使这两个类都利用了匿名内部类的概念。 1类具有静态内部类。 第2类使用它。 但是我不明白如何调用内部类的方法。 请帮帮我。

1类

public class outerclass {
  outerclass() {
    System.out.println("Constructor of new class");
  }

  public void showthis(String str) {
    System.out.println(str);
  }

  static class insideclass {
    insideclass() {
      System.out.println("This is inside class constructor");
    }

    public void nowshowthis(String str) {
      System.out.println(str);
    }
  }
}

2级

public class helloworld {
  public static void main(String args[]) {
    //this is an object of the outer class
    outerclass example=new outerclass();
    //How do i make an anonymous inner class and call the method "nowshowthis()"
  }
}

让我摆脱我的紧迫问题! 如果您的内部类处于非静态状态,则这是实例化它的方法:(假设exampleouterclass类型的对象)

  example.new insideclass().nowshowthis("my String")

对于static public内部类,你甚至不需要外部类的一个实例。 只需执行此操作(就像访问公共静态变量一样)

new outerclass.insideclass().nowshowthis("my String")

你尝试过这个吗?

这是怎么回事? 就您而言,您并不是真正在处理匿名内部类。 它实际上只是一个普通的香草内部类。 (我无法合理化您为什么要这么做。)

那么什么是匿名类,在哪里使用呢? 匿名类就像是一次使用的类的实例。 当您实现某些接口时,其中一个例子浮出水面……但是您无需其他方式使用它。 例如,您要将处理程序附加到按钮。 您可以按照这种方式进行操作(假设的示例)

   MyButtonInterface obj= new MyButtonInterface(){
      @Override
      onClick(Model obj){
             //save model in DB
       }
   }
   UI.add(obj, "specificId");

你看?

匿名内部类是在另一个类的方法的主体内创建和定义的。 本质上,您是根据抽象定义动态创建具体的类。 到目前为止,您的InnerClass类实际上拥有的只是一个普通的内部类,意味着非匿名的。

如果要尝试使用匿名内部类,我想到的最简单的方法是将InnerClass更改为接口,如下所示:

public interface InnerClass{
    public void doSomething();
}

因此,目前,InnerClass确实蹲下; 在定义之前,它没有任何意义。 接下来,您将需要更改OuterClass的工作方式。 像这样更改showThis()函数:

public showThis(InnerClass innerObj){
    innerObj.doSomething();
}

现在,我们有您的外部类要求内部类实例做某事,但是我们仍然没有定义我们想要它做什么。 这就是魔术发生的地方-在您的main方法中,您将定义内部类实例的实际外观:

public static void main (String[] args){
    OuterClass outer = new OuterClass();

    // This is the key part: Here you are creating a new instance of inner class 
    // AND defining its body. If you are using Eclipse, and only write the 
    // new InnerClass() part, you'll notice that the IDE complains that you need 
    // to implement the doSomething() method, which you will do as though you
    // were creating a plain 'ol class definition
    outer.showThis(new InnerClass(){ 
        public void doSomething(){
            System.out.println("This is the inner anonymous class speaking!");
        }
    });
}

实际上,我没有过多使用匿名内部类,但是了解它们很有用。 在进行GUI编程时,我经常使用它们来定义GUI控制事件(例如按钮单击)的侦听器。

另外,正如其他人所提到的,请记住,Java标准将类名的第一个字母大写,在此已完成。 您将要遵循该标准,因为它使其他人更轻松地阅读您的代码,并且一目了然,您可以很容易地分辨出何时查看类以及何时查看对象。

无论如何,希望能有所帮助。

insideclass是一个非静态类,因此必须通过外部类的实例进行访问,如下所示:
new outerclass().new insideclass().nowshowthis();

那不是匿名的内部类。 这是一个匿名内部类的示例:

class InnerClassDemo {
  public static void main(String[] args) {
    ActionListener a = new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
      }
    };
    // now a is the only instance of an anonymous inner class implementing the ActionListener interface
  }
}

当然,您也可以使用自己的接口或类来执行此操作:

class InnerClassDemo {
  public class InsideClass {
      InsideClass() {
          System.out.println("This is inside class constructor");
      }

      public void nowshowthis(String str) {
          System.out.println(str);
      }
  }

  public static void main(String[] args) {
    InsideClass anonym = new InsideClass() {
      @Override
      public void nowshowthis(String str) {
          System.out.println("anonymous inner class override: "+str);
      }
    }
    InsideClass normalInstance = new InsideClass();
    anonym.noshowthis("test");
    normalInstance.noshowthis("test");
  }
}

您的输出将是

anonymous inner class override: test
test

因此, anonymInsideClass的匿名内部类实现的InsideClassnormalInstance只是类InsideClass的常规实例。

public class HelloWorld {

    public static void main(String args[])
        {


        outerclass.insideclass example= new outerclass.insideclass();

        example.nowshowthis("Hello");


    }
}

或者,将nowshowthis方法设为静态,可以这样调用它:

outerclass.insideclass.nowshowthis("Howdy. This method is static.");

暂无
暂无

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

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