2011-04-26 76 views
0
class Outer{ 

    public void Method(){ 

    int i=10; 
    System.out.println(i); 
    Class InsideMethod{ 
     // 
    } 
} 

問題的方法內部定義的類的實例:我怎樣才能調用InsideMethod對象的方法外如何調用外部類

+0

你能提供一個例子嗎? – 2011-04-26 10:06:53

回答

3

如果我理解正確的話,你想要什麼,你可以做:

OuterClass.this 
2

外 類的方法內部定義

如果其的方法則其範圍限於僅該方法中定義。

+0

我們可以稱之爲新的類名()()方法。 – Samarth2011 2011-04-26 10:15:51

+0

是的,我們能。但是我們無法訪問該方法中的變量。 – 2011-04-26 10:18:05

5

此片段說明的各種可能性:

public class Outer { 

    void onlyOuter() { System.out.println("111"); } 
    void common() { System.out.println("222"); } 

    public class Inner { 
    void common() { System.out.println("333"); } 
    void onlyInner() { 
     System.out.println("444");// Output: "444" 
     common();     // Output: "333" 
     Outer.this.common();  // Output: "222" 
     onlyOuter();    // Output: "111" 
    } 
    } 
} 

注:

  • 內部類的方法隱藏了外類的類似命名的方法。因此,common();呼叫調度從內部類實現。
  • 用於指定要從外部類分派方法的使用OuterClass.this構建體(繞過隱藏)
  • 呼叫onlyOuter()調度從OuterClass該方法,因爲這是最內封閉類定義這種方法。
0

從我瞭解你的問題......(見下面的例子),外部類的方法中定義的類「難以捉摸」的實例不能從法的外部引用「 doOuter」。

public class Outer { 

    public void doOuter() { 
     class Elusive{ 

     } 
     // you can't get a reference to 'e' from anywhere other than this method 
     Elusive e = new Elusive(); 
    } 

    public class Inner { 

     public void doInner() { 

     } 
    } 

}