Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I was wondering if it's valid to initialize an instance of a class within the same class? For example:

public class Person()
{ 
   string name;
   string age;
   public Person getPerson()
   { 
       Person p1=new Person();
       //some logic here
       return p1
    }
}

I ended up doing that for a part of my code at work and thus wanted to know if there are any potential problems with doing something like this.

share|improve this question
    
When the instance returned by getPerson is not influenced by the Person instance you call it on, the function should be declared and called static. –  Philipp Jul 31 '13 at 14:42
add comment

2 Answers

Yes, it is valid.

That's called a factory method.

The Calendar class, for example has a getInstance() method.

That's also useful when implementing the Singleton pattern.

Here you have a SO question about when to use a factory method.

share|improve this answer
1  
2  
Should be noted that for a factory, getPerson() should be static. –  Steven Burnap Jul 31 '13 at 3:34
3  
If it is not static, and it copies data from the current instance to the new instance, it is a clone method. –  rwong Jul 31 '13 at 4:05
add comment

Yes. Often done when you need to build large, dynamic, self-maintaining structures like Trees:

class Tree {

  public IComparable Value;
  private Tree Left;
  private Tree Right;

  public Add (IComparable value) {
    if (this.Value == null) {
      this.Value = value;

      // RIGHT HERE!
      this.Left = new Tree();
      this.Right = new Tree();

    } else {
      if (value > this.Value) {
        this.Right.Add(value);
      } else {
        this.Left.Add(value);
      }
    }
  } // Add()

} // class Tree
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.