Search code examples
javainterfacestack-overflow

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.

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

Solution

  • As mentioned by other, It goes into a Recursive Loop. Adding an Image for better Understanding .

    enter image description here