简体   繁体   中英

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

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

C c = new C();
  1. it has to initialize the member variables of the class C - here they are A a and B b .

  2. To initialize them, you create an instance of C . Goto 1 .

when you are initializing 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() . It will cause in 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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