Why is this code resulting in StackOverflow error:

Why is this code resulting in StackOverflow error:

Class C 实现了 2 个接口 A 和 B。我只是想打印 class 值来验证多接口实现,但我得到了 Whosebug 错误。

 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();
        }
    }

当您从 main

创建 C 的实例时
C c = new C();
  1. 它要初始化classC的成员变量——这里是A aB b

  2. 要初始化它们,您需要创建一个 C 的实例。转到 1.

当您初始化 C c = new C(); 时,它正在实例化它的实例变量,您已将其声明为

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

在这里你可以看到它会再次去构造 C 并再次 n 再次找到 ab 并将实例化为 C()。它会导致 Whosebug

这是因为每次创建 'C',最终都会创建两个 C,然后再创建四个 C,依此类推。

您可以这样做,

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();
              }


        }

然后调用测试方法,

public class MultiInherit{

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

正如其他人所提到的,它进入了一个递归循环。 添加图像以更好地理解。