简体   繁体   English

为什么此代码导致StackOverflow错误:

[英]Why is this code resulting in StackOverflow error:

Class C implements 2 interfaces A and B. I just wanted to print class values to verify Multiple Interface implements, instead I got StackOverflow error. C类实现2个接口A和B。我只想打印类值以验证Multiple Interface实现,相反,我遇到了StackOverflow错误。

 interface A {
        void test();
    }

    interface B {
        void test();
    }


    class C implements A, B {
        A a = new C();
        B b = new C();

        @Override
        public void test() {
            System.out.println(a.getClass());
            System.out.println(b.getClass());
        }
    }


    public class MultiInherit{

        public static void main(String args[]){
            C c = new C();
            c.test();
        }
    }

As mentioned by other, It goes into a Recursive Loop. 正如其他人所述,它进入了递归循环。 Adding an Image for better Understanding . 添加图像以便更好地理解。

在此处输入图片说明

When you create an instance of C from main 当您从main创建C的实例时

C c = new C();
  1. it has to initialize the member variables of the class C - here they are A a and B b . 它必须初始化类C的成员变量-在这里它们是A aB b

  2. To initialize them, you create an instance of C . 要初始化它们,请创建C的实例。 Goto 1 . 转到1

when you are initializing C c = new C(); 当您初始化C c = new C(); it is instantiating it's instance variables and which you have declared as 它实例化了它的实例变量,并且您已经声明为

A a = new C();
B b = new C();

here you can see it will again go to construct C and will again n again find a and b and will instantiate as C() . 在这里,您可以看到它将再次构造C,并且n将再次找到ab并将实例化为C() It will cause in stackOverflow 它将导致stackOverflow

Its because everytime you create a 'C', you end up creating two C s which will then create four C s and so on. 这是因为每次创建“ C”时,最终都会创建两个C ,然后将创建四个C ,依此类推。

You can do this instead , 您可以改为这样做,

interface A {
              void test();
        }

        interface B {
              void test();
        }


        class C implements A, B {
              A a ;
              B b ;

              @Override
              public void test() {
                    System.out.println(a.getClass());
                    System.out.println(b.getClass());
              }

              public void createObjects(){
                    a = new C();
                    b = new C();
              }


        }

and then call the test method , 然后调用测试方法,

public class MultiInherit{

    public static void main(String args[]){
        C c = new C();
        c.createObjects();
        c.test();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM