是否可以显式访问嵌套类的包含类的实例成员?

时间:2012-04-05 18:51:26

标签: java nested-class scoping

java中是否有关键字允许在嵌套类中显式调用包含实例(或其超类)的成员?

SCENARIO

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
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

哦,完全。只需使用Subclass.this.doSomething()Subclass.super.doSomething()即可获得超类方法。