Is it okay for a class to have a field of its own type

后端 未结 4 868
暗喜
暗喜 2021-01-18 12:22

I did the following, i got a stackoverflow error after some time, and I understand why it was.

public class Cat {
    String name=\"default name\";
    Cat i         


        
4条回答
  •  没有蜡笔的小新
    2021-01-18 12:47

    Classes like this exist all the time.

    Consider linked lists or trees, e.g.,

    class ListNode {
      ListNode next;
      // Etc.
    }
    
    class TreeNode {
      TreeNode left;
      TreeNode right;
      // Etc.
    }
    

    You wouldn't initialize the "child" objects in the constructor, you'd add them later.

    In your example you'd need to have a method that created the insideCat at a later time. In general you wouldn't create child objects that had the exact same state, there'd be something to differentiate them either at construction time, in which case you could have a "oh god stop creating these now" condition, or while they were being added, e.g., you'd add them via a method and not in a constructor.

提交回复
热议问题