2016-06-13 76 views
1

在Java中,我使用擴展B的類A中的匿名類。如何從這個匿名類訪問B?我不能使用關鍵字super,因爲這意味着超類的匿名類,而不是超類的AJava:從匿名類獲取超類

public class A { 

    void foo() { 
     System.out.println("Good"); 
    } 
} 

public class B extends A { 

    void bar() { 
     Runnable r = new Runnable() { 

      @Override 
      public void run() { 
       foo(); // Bad: this call B.foo(), not A.foo() 
       // super.foo(); // Bad: "Method foo is undefined for type Object" 
      } 

     }; 
     r.run(); 
    } 

    @Override 
    void foo() { 
     System.out.println("Bad"); 
    } 
} 
+0

我懷疑你能做到這一點,考慮到類只有*引用*到'B' ... –

回答

1

請致電如休耕:

B.super.foo();

這種變化B類看起來如下之後:

public class B extends A { 

    public static void main(String[] args) { 
     new B().bar(); 
    } 

    void bar() { 
     Runnable r = new Runnable() { 

      @Override 
      public void run() { 
       B.super.foo(); // this calls A.foo() 
      } 

     }; 
     r.run(); 
    } 

    @Override 
    void foo() { 
     System.out.println("Bad"); 
    } 
} 
3

run,你可以當我改變了,然後就跑B.bar()我得到Good改變foo()B.super.foo();

1

在這種情況下,你需要有資格this捕捉外部類,B

B.this.foo() 

或者,在你的情況下,只要你想超類,使用

B.super.foo() 

相關Java的部分語言規格:

+1

執行「Bad」方法。 –

+0

啊,錯過了。固定 –