2012-04-05 71 views
1

是否有在Java關鍵字,以允許含有實例的成員的顯式調用(或它的超類的)從嵌套類內?是否可以顯式訪問包含類的嵌套類的實例成員?

情景

public class Superclass { 
    public void doSomething() { 
     // do something that's of interest to the superclass 
    } 
} 

public class Subclass extends Superclass { 
    @Override 
    public void doSomething() { 
     // do something that's of interest to the subclass 
     // possibly call super.doSomething() 
    } 

    private class NestedClass { 
     private void doSomething() { 
      // do something that's of interest to the nested class 
      // calling doSomething() here without an explicit scope 
      // specifier results in a stack overflow 
     } 

     private void doSomethingElse() { 
      if (somethingOfInterestToTheSubclassIsNotImportant) { 
       // just invoke the superclass's doSomething() method 
      } else { 
       // invoke the subclass's doSomething() method 
      } 
     } 
    } 
} 

回答

2

哦,完全。只需使用Subclass.this.doSomething()Subclass.super.doSomething()即可獲取超類方法。

+0

完美!請添加'Subclass.super.doSomething()',我會接受你的答案。 – arootbeer 2012-04-05 19:11:25

+0

......咦。我不知道你可以這樣做。 – 2012-04-05 19:15:54