Is it OK to reference 'this' when initializing a field?
        Posted  
        
            by parxier
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by parxier
        
        
        
        Published on 2010-04-21T01:25:47Z
        Indexed on 
            2010/04/21
            1:33 UTC
        
        
        Read the original article
        Hit count: 373
        
java
|best-practices
Is it OK to reference this when initializing a field?
public class MainClass {
  private SomeFieldClass field = new SomeFieldClass(this);
  public MainClass() {}
}
Or is it better to do that in constructor?
public class MainClass {
  private SomeFieldClass field;
  public MainClass() {
    this.field = new SomeFieldClass(this);
  }
}
What is the best practice? I believe first option is better for unit testing and dependency injection. Are there any problems with it?
© Stack Overflow or respective owner