This code shows error at run time:
class Animal {
Animal object1 = new Animal();
public static void main(String[] args) {
Animal obj =
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.