簡體   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