Declaring an instance of a class inside that class

后端 未结 3 2122
不思量自难忘°
不思量自难忘° 2020-12-10 15:54

This code shows error at run time:

class Animal {
    Animal object1 = new Animal();

    public static void main(String[] args) {     
        Animal obj =          


        
3条回答
  •  渐次进展
    2020-12-10 15:58

    Short answer infinite recursion.

    Long answer if you want recursive data structures like that, you can do something like this:

    public class A {
      A object1;
      public A(A member) { 
        this.object1 = member; 
      }
      public static void main(String[] args) {
        A item = new A(new A(null)); // note the base case/termination of the recursion!
      }
    }
    

    Or:

    public class B {
      B object1;
      public void init() {
        object1 = new B();
      }
      public static void main(String[] args) {
        B item = new B();
        item.init(); 
        // now item.object1 != null, but item.object1.object1 == null
      }
    }
    

    In either case, you will have “sentinel” or “leaf” nodes in your data structure, which point to a null value.

提交回复
热议问题