簡體   English   中英

局部內class

[英]Local inner class

我已經通讀了內部 class 教程並且不明白一件事。 據說內部 class 包含對外部 class 的隱藏引用,所以我通過這個簡單的 class 提出了幾個問題:

public class OuterClass {

public void doSomething() {
    JButton button = new JButton();
    button.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {                
      }
    });
  }
}

所以我們有一個本地內部 class 位於方法doSomething()中,我有一些問題。

  1. 這個本地內部 class 是否持有對 OuterClass 的引用,因為它是本地的?

  2. 在方法doSomething()終止后,這個本地內部 class 是否仍然是 memory ?

  3. 是否存在 OuterClass 符合 GC 條件但本地內部 class 仍被其他類引用的情況? 會發生什么?

  1. 是的,內部 class 引用了OuterClass實例。

    您可以通過在方法中訪問OuterClass.this來驗證這一點。

  2. 是的,內部 class 實例將在方法終止后繼續存在。

    離開該方法不會影響 object 的使用壽命。 就像所有其他 object 一樣,一旦不再引用它,它將有資格進行 GC。 由於JButton將持有對它的引用,因此它將保留在 memory 中。

  3. 只要內部OuterClass實例可以訪問,OuterClass 實例就不能成為 GC 的條件。

    The reason for that is #1: the inner class instance has a reference to the outer class instance, which means that the outer class can not become eligible for GC as long as the inner class is not eligible at the same time (ie both are不再可達)。

暫無
暫無

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

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