سؤال

Here is the code where I am updating the instance variable x of OuterClass by static variable of StaticInner. I understand that the static inner classes cannot refer directly to instance variable of outer classes. I am using an instance of outerclass to refer to its instance variable 'x' and update it. This goes into stackoverflow error. The code complies fine. The last line in the code does not compile which I commented out. I don't understand what the problem with that line.

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

}
هل كانت مفيدة؟

المحلول

You have a circular dependency in the constructors, resulting in a recursive call between them

Outer(){
  createInner()
}

Inner(){
   createOuter()
}

This won't work (unless you use reflection, but that defeats the purpose).

You need to structure the classes so there is a linear dependency. I recommend passing the outer instance to the inner constructor

Outer(){
   inner = new Inner(this);
}

Inner(Outer o){
  myouter = o;
}

نصائح أخرى

Don't qualify "new" with an outer class instance. That only applies to inner classes. Just instantiate the nested class like any other.

You should not need to mention the outer class at all when working with a static nested class inside the outer class.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top