Java:在嵌套静态类中引用外部类 [英] Java: reference outer class in nested static class
问题描述
我有一个这样的类结构:
public class OuterClass {
private static class InnerClass {
public void someMethod() {
OtherClass.otherMethod(<???>);
}
}
表示其他某些类OtherClass
的静态方法:
public class OtherClass {
public static void otherMethod(OuterClass) {
....
}
}
我正在尝试找出要代替<???>
的内容.如何从内部静态类中引用外部类的实例?我想做的是引用OuterClass
的隐式this
.
您显然需要OuterClass
类型的对象:
public void someMethod() {
OuterClass oc = new OuterClass();
OtherClass.otherMethod(oc);
}
如果您的内部类不是静态的,则可以执行以下操作:
//remove static here
private class InnerClass {
public void someMethod() {
OtherClass.otherMethod(OuterClass.this);
}
}
您应该了解嵌套类之间的区别-静态和非静态.静态嵌套类是与其他类一样简单的类,只是在其他类中定义(通常是由于封装原理).内部静态类实例不了解外部类实例.
嵌套的内部类(非静态)要求内部类的对象存在于外部类的实例中.这就是为什么您可以通过OuterClass.this
访问它的原因.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
.
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
.
这篇关于Java:在嵌套静态类中引用外部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!