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
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.
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.
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
!
There is nothing wrong in having an instance member of same class. an Employee has a manager and the manager is also an Employee
public class Employee{
private Employee manager;
//getters setters and constructor
}