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

后端 未结 4 806
暗喜
暗喜 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:56

    There can be multiple constructors. Thus, you can have another constructor

    public Cat(){...}
    

    That would allow you to create an inside Cat. Afterwards you could create another Cat that contains the inside Cat. Obviously, the design might not be great here, depending on your needs. Dave Newton's answer about linked list is a great real world example of this usage.

提交回复
热议问题