簡體   English   中英

有沒有辦法實例化一個匿名內部類?

[英]Is there any way to instantiate an anonymous inner class?

有沒有辦法從main方法訪問匿名類的方法? 如果是這樣,訪問這種方法的語法是什么?

class Demo {
   void show() {
      System.out.println("i am in show method of super class");
   }
}
class Flavor1Demo {

   //  An anonymous class with Demo as base class
   static Demo d = new Demo() {
       void show() {
           super.show();
           System.out.println("i am in Flavor1Demo class");
       }
   };
   public static void main(String[] args){
       d.show();
   }
}

匿名類在您需要它們的同時被實例化。 他們沒有名字。 如果您使用 Swing 或 applet 進行編碼,那么實際上匿名實例化的ActionListeners or EventHandlers

如果您至少有一個匿名類的實例(對象),乍一看似乎是:

class Demo {
   void show() {
      System.out.println("i am in show method of super class");
   }
}
public class Flavor1Demo {

   //  An anonymous class with Demo as base class
   static Demo d2 = new Demo() {
       void show() {
           super.show();
           System.out.println("i am in Flavor1Demo class");
       }
   };
   public static void main(String[] args){
       d2.show();
       try {
        Demo v = d2.getClass().newInstance();
        System.out.println("Object created"+v.getClass().getTypeName()); // Canonical is null
    } catch (InstantiationException | IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   }
}

我很驚訝,匿名 cls 似乎是靜態類型,不需要對父級的隱藏引用? 好像沒有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM