How can a class have a member of its own type, isn't this infinite recursion?

JavaOopClass

Java Problem Overview


Say I define a class that has as a member a variable of the same type as itself.

public class Abc {
    private Abc p;
}

This actually works, much to my surprise.

Why I think it shouldn't: creating an instance of Abc, it contains a variable of type Abc, which contains a variable of type Abc, which contains a variable of type Abc, which .....

Obviously I'm wrong, could someone enlighten me as to how?

Java Solutions


Solution 1 - Java

You're only declaring the variable and not creating it. Try creating it at declaration or in the constructor and let me know what happens:

public class Abc {
   private Abc p = new Abc(); // have fun!
   
   public static void main(String[] args) {
      new Abc();
   }
}

Incidentally, if you don't create it in the class, but rather accept a reference to it in a getter method or a constructor parameter, your code will work just fine. This is how some linked lists work.

Solution 2 - Java

The difference lies in compile-time vs run-time checks.

In the first case (compile time), you are declaring that you will have a reference to a value of type Abc in this instance. The compiler will be aware of this when it checks for proper semantics, and since it knows the type upon compile time, it sees no issue with this.

In the second case (run time), you will actually create a value for this reference to refer to. This is where you could potentially get yourself into trouble. For example, if you said the following:

public class Abc {
    private Abc p;

    public Abc() {
        p = new Abc();
    }
}

This could lead you into trouble for the exact reason you cited (recursion that contains no base case and will continually allocate memory until you've run the VM out of heap space).

However, you can still do something similar to this and avoid the infinite recursion. By avoiding creating the value during construction, you put it off until a method is called for. In fact, it's one of the common ways to implement the singleton pattern in Java. For example:

public class Abc {
    private Abc p;

    private Abc() {  // Private construction. Use singleton method
    }

    public static synchronized Abc getInstance() {
        if (p == null)
            p = new Abc();

        return p;
    }
}

This is perfectly valid because you only create one new instance of the value, and since run-time will have loaded the class already, it will know the type of the instance variable is valid.

Solution 3 - Java

When you want to model some real-world scenarios, you might have to use this notion. For example, think of a Tree's branch. A tree's branch might have n number of branches on it. Or from computer science background, think of a linked list's Node. A node will have reference to the node next to it. At the end, the next will contain a null to indicate end of the list.

So, this is only a reference, indicating that this type might refer to one of it's own. Nothing more.

Solution 4 - Java

As the chosen answer states, it's okay because the variable is not being instantiated, but rather it is accepting a reference from a set method or constructor argument. So you see, it's just a reference, just an address.

However though, there is a way of instantiating it without causing the nightmare loop, and that's by declaring it as static. This sort of bends the recursion rule because a static member is not on an object level but on a class level.

So...

public class Abc
{
    public static Abc p = new Abc ();
}

Works just fine because the variable 'p' is not really affected by the instantiation of the Abc class. It's almost the equivalent of creating the 'p' object in another class.

Remember that I can do this...

 public class Abc
 {
     public static Abc p = new Abc ();

     public static void main(String [] args)
     {
         Abc.p;
     }
 }

Without creating a new object of Abc in the main method. That's how statics work, they're virtually unaffected by instantion of objects, and in the case of your question, they are the exception to the recursion rule.

Solution 5 - Java

Summarizing some of the answers here.

The class contains reference to one of its own kind.The best analogy in real world would be of a treasure hunt. A Clue place has some data and a clue in it which leads to another clue place which again you know repeats.

It is not saying that a clue place has another clue place in it, the kind of which you are seeming to infer.

Solution 6 - Java

The basic use of this may be the Linked list in the data structure. It is a core concept in the Linked list, a reference from one node to the another node. The class Node consists of the basic element for Linked list.

class Node{
	private int value;
	private Node next; //reference, as a pointer to another node, →
	
	Node(){
		this.value=0;
		this.next=null;
	}
	Node(int value){
		this.value=value;
		this.next=null;
	}
	Node(int value,Node next){
		this.value=value;
		this.next=next;
	}
	public int getValue() {
		return this.value;
	}
	public void setValue(int value) {
		this.value=value;
	}
	public Node getNext() {
		return this.next;
	}
	public void setNext(Node next) {
		this.next=next;
	}
}

And we can connect these node by using the reference.

class Linkedlist{
    Node head = new Node();
    Node one = new Node();
    Node two = new Node();

    // Assign data values 
    one.value = 1;
    two.value = 2;

    // Connect nodes 
    one.next = two;
    two.next = NULL;

    //Save address of first node in head
    head = one;
}

Head → 1 next → 2 next → NULL

Therefore, this is only a reference type connecting one node to the another node in the data structure of the linked list.

Solution 7 - Java

While we are talking about "recursion", the "execution" of code is the point we are considering. Yes, it is "dynamic" if a "recursion" is occurring.

In type declaration, a variable that contains a member, which is the type of containing variable, is "static". For example, a box may contain another box inside it, and so on. But there is finally a smallest box which doesn't contain anything. For a chain of railway carriages, every carriage has a member to next carriage except the last carriage.

In program, the static data must be "finite"(You don't have "infinite" space of memory). The execution of code may be "infinite". But there is an exception. Just imaging a circle of chain.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjasonView Question on Stackoverflow
Solution 1 - JavaHovercraft Full Of EelsView Answer on Stackoverflow
Solution 2 - JavapseudorambleView Answer on Stackoverflow
Solution 3 - Javaring bearerView Answer on Stackoverflow
Solution 4 - JavaWTRIXView Answer on Stackoverflow
Solution 5 - JavaRakeshView Answer on Stackoverflow
Solution 6 - JavaLEO CHENView Answer on Stackoverflow
Solution 7 - JavaMike LueView Answer on Stackoverflow