2015-03-31 106 views
5

我最近遇到了這樣的事情訪問父類的時候......解決歧義從匿名類

public final class Foo<T> 
implements Iterable<T> { 

    //... 

    public void remove(T t) { /* banana banana banana */ } 

    //... 

    public Iterator<T> Iterator { 
     return new Iterator<T>() { 

      //... 

      @Override 
      public void remove(T t) { 
       // here, 'this' references our anonymous class... 
       // 'remove' references this method... 
       // so how can we access Foo's remove method?   
      } 

      //... 

     }; 
    } 
} 

有沒有辦法做我試圖同時保持這是一個匿名類?或者我們必須使用內部類還是其他什麼?

+0

[從內部類對象獲取外部類對象]的可能重複(http://stackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the -inner-class-object) – Raedwald 2015-04-02 07:06:01

回答

7

您可以使用Classname.this訪問封閉類。因此,在你的例子:

public void remove(T t){ 
    Foo.this.remove(t); 
} 
2

Foo.this.remove(T)就可以了爲你。

+5

已經有完全相同的答案。請注意他們,而不是張貼一個重複的。 – 2015-03-31 14:25:53