2011-02-15 131 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; 
}