2011-02-15 129 views
3

如何從內部類中的方法獲取父對象?嵌套類的對象如何訪問它們嵌套的對象?

class OuterClass { 
    public outerMethod() { 
     // this refers to the object in the outer class 
    } 
    class InnerClass { 
     public innerMethod() { 
      // this refers to the object in the inner class 
      // How do I get my current parent object 
     } 
    } 
} 

一種方法是添加像

public OuterClass getthis() { 
    return this; 
} 

任何其他建議的方法?有沒有從java本身的方式?

+0

更新了類名。對困惑感到抱歉。 – EFreak 2011-02-15 10:28:15

回答

8
outerClass.this.method() 

類名應該以大寫字母開頭,這樣可以減少這種情況下的混淆。

2

我想這應該這樣做:

class outerClass { 
    public outerMethod() { 
     // this refers to the object in the outer class 
    } 
    class innerClass { 
     public innerMethod() { 
      // Here's how to get and use the parent class reference 
      outerClass daddy = outerClass.this; 
      daddy.outerMethod(); 

      // However, you can also just call the method, and 
      // the "outer this" will be used. 
      outerMethod(); 
     } 
    } 
} 

BTW - 這是嚴重不良作風來聲明一個類是不以大寫字母開頭的名稱。如果您選擇忽略這些約定,預計會多次提醒您,重複

0

outerClass.this有竅門。爲了清楚起見,你的類名應該以大寫字母開頭。

0
outerClass.this.outerMethod(); 

這顯然不適用於靜態內部類,因爲沒有外部類的封閉實例。

而在我忘記之前,請閱讀Java Code Conventions。 CLass應該以大寫字母開頭。

0
public outerClass getthis() { 
    return outerClass.this; 
}