2012-04-05 70 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