问题
I have a class structure like this:
public class OuterClass {
private static class InnerClass {
public void someMethod() {
OtherClass.otherMethod(<???>);
}
}
which refers to a static method of some other class OtherClass
:
public class OtherClass {
public static void otherMethod(OuterClass) {
....
}
}
I am trying to figure out what to put in place of the <???>
. How do I refer to the instance of the outer class from within the inner static class? What I would like to do is to refer to the implicit this
of the OuterClass
.
回答1:
You obviously need an object of OuterClass
type:
public void someMethod() {
OuterClass oc = new OuterClass();
OtherClass.otherMethod(oc);
}
In case that your inner class is not static, then you could do:
//remove static here
private class InnerClass {
public void someMethod() {
OtherClass.otherMethod(OuterClass.this);
}
}
You should know the different between nested classes - static and non static. Static nested classes are simply classes like every other, just defined within other class (usually because of encapsulation principle). Inner static class instances have no knowledge of outer class instance.
Nested inner classes (non static) mandate that an object of the inner class exist within an instance of the outer class. That's why you can access it via OuterClass.this
.
回答2:
The simpliest way is to pass an instance of the outerClass in the constructor or in the method since the innerClass don't know this class.
like this:
public void someMethod(OuterClass outerClass) {
OtherClass.otherMethod(outerClass.myMethod());
}
来源:https://stackoverflow.com/questions/31835630/java-reference-outer-class-in-nested-static-class