tags:

views:

174

answers:

5

What is it called when an object has an object of the same type inside of itself?

Example:

public class Foo{

     public Foo myFoo;

}
+4  A: 

Recursive containment.... :)

John Weldon
Did you just make that up?
StriplingWarrior
Yes, there is also the term "recursive composition" (http://en.wikipedia.org/wiki/Object_composition#Recursive_composition)
0xA3
Yes. :) Recursive Composition is good too :)
John Weldon
+3  A: 

A StackOverflowException waiting to happen?

Depends on the what myFoo is which will depend on the language.In Java the code is valid, myFoo is just a reference to a Foo, not an actual Foo itself.In c++ myFoo would be an actual Foo(not a pointer to a Foo) and yea, you'd get some issues(it wouldn't compile though)
nos
Yeah, but it was all in jest. Every time I've dealt with students new to classes in java they'd have something like this, try to call the constructor from the constructor and get this exception.
I think 1. hlfrk414 is being facetious and 2. he or she is warning against infinite recursion when you traverse the object. In practice, of course, it's feasible to guard against that in most situations (which doesn't necessarily mean it's done correctly...).
Edmund
+14  A: 

I don't think there's any specific name for this. Although this concept is used in many different common programming constructs. For instance, when representing a graph, tree, or linked list, the nodes usually have references to other nodes that they are linked/connected to.

Kibbee
Yes I'd call it a tree or a list or whatever its shape is.
ChrisW
+5  A: 

It means that Foo is a 'recursive data structure'. Examples of this are trees, graphs, linked lists, etc. There aren't many significant programs written that don't use at least some recursive structures, e.g. in any SQL server implementation it's pretty common that the query plan that gets executed will be defined in a similar way. As a tiny example, the WHERE clause might get translated to a FilterNode that acts on data received from some other Node (like a table scan):

public interface Node { }

public class FilterNode implements Node {
    public Node underlyingNode;
    public Condition filterCondition;
}

In many cases the overall structure forms a directed acyclic graph, which means it's easy to safely traverse it recursively. But if it's got cycles then you need to be careful that you don't get into infinite recursion (which is what another answer above is humorously warning about).

Edmund
+1  A: 

To add to what Kibbee said, this is a type of a composite pattern

Rado