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

后端 未结 4 810
暗喜
暗喜 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 13:03

    There are many examples of self referencing data structures that are valid. Think of a LinkedList. Each LinkNode has a data field, and a pointer to the next LinkNode.

    class LinkNode {
        int data;
        LinkNode nextLink;
    
        public LinkNode(int d1) {
            data = d1;
            nextLink = null;
        }
        ...
    }
    
    class LinkedList {
        private LinkNode first;
    ...
    }
    

    Your StackOverflow problem stems from the fact that creating an instead of X requires the creation of another X, ad-infinitum.

    Just think of your Cat example. Why would instantiating a Cat require of all things...another Cat!

提交回复
热议问题