Java中静态内部类中的stackoverflow错误?
下面是代码,我正在通过Java中静态内部类中的stackoverflow错误?,java,inner-classes,static-class,Java,Inner Classes,Static Class,下面是代码,我正在通过StaticInner的静态变量更新OuterClass的实例变量x。我知道静态内部类不能直接引用外部类的实例变量。我正在使用outerclass的实例引用其实例变量“x”并对其进行更新。这将导致stackoverflow错误。代码符合要求。代码中的最后一行没有编译,我已经注释掉了。我不明白那条线有什么问题 public class OuterClass { private int x = 10; private static int y = 15;
StaticInner
的静态变量更新OuterClass
的实例变量x
。我知道静态内部类不能直接引用外部类的实例变量。我正在使用outerclass的实例引用其实例变量“x”并对其进行更新。这将导致stackoverflow错误。代码符合要求。代码中的最后一行没有编译,我已经注释掉了。我不明白那条线有什么问题
public class OuterClass {
private int x = 10;
private static int y = 15;
private static StaticInner si=null;
public OuterClass() {
setStaticInner();
this.x=si.ic.x;
}
public static class StaticInner {
private static int z = 20;
private OuterClass ic = new OuterClass();
public void increment() {
OuterClass.y+=z;
z+=OuterClass.y;
ic.x+=10;
}
}
public void setStaticInner(){
si=new StaticInner();
}
public static void main(String[] args){
OuterClass ic = new OuterClass();
ic.si.increment();
System.out.println(ic.x);
//OuterClass.StaticInner sb1 = ic.new StaticInner(); This line does not compile.
}
}
您在构造函数中有一个循环依赖项,导致它们之间的递归调用
Outer(){
createInner()
}
Inner(){
createOuter()
}
这是行不通的(除非您使用反射,但这违背了目的)
您需要构造类,以便存在线性依赖关系。我建议将外部实例传递给内部构造函数
Outer(){
inner = new Inner(this);
}
Inner(Outer o){
myouter = o;
}
您在构造函数中有一个循环依赖项,导致它们之间的递归调用
Outer(){
createInner()
}
Inner(){
createOuter()
}
这是行不通的(除非您使用反射,但这违背了目的)
您需要构造类,以便存在线性依赖关系。我建议将外部实例传递给内部构造函数
Outer(){
inner = new Inner(this);
}
Inner(Outer o){
myouter = o;
}
不要用外部类实例限定“new”。这只适用于内部类。只需像其他类一样实例化嵌套类
在使用外部类中的静态嵌套类时,不需要提及外部类。不要用外部类实例限定“new”。这只适用于内部类。只需像其他类一样实例化嵌套类
在使用外部类中的静态嵌套类时,不需要提及外部类