Is it possible to refer to 'this' when initializing a field?

Is it possible to refer to thiswhen initializing a field?

public class MainClass {

  private SomeFieldClass field = new SomeFieldClass(this);

  public MainClass() {}

}

Or is it better to do this in the constructor?

public class MainClass {

  private SomeFieldClass field;

  public MainClass() {
    this.field = new SomeFieldClass(this);
  }

}

What is the best practice? I believe the first option is better for unit testing and dependency injection. Are there any problems with this?

+3
source share
3 answers

The question is a bit unclear. Are you worried about passing this to the constructor, or about using this field in the constructor body, or about initializing the field in the constructor, and not in the class body?

I personally prefer to use this prefix when referring to class members, but this is a matter of style.

. , (, ), .

( ), , , , - . (, createAssociatedSomeObject())

+4

this ( ) (1) , (2) MainClass.

+4

Both are acceptable. However, you would use the second if you could throw an exception that you can handle. I recommend the second, as this localizes the initialization in one place and can be called from other constructors.

+2
source

Source: https://habr.com/ru/post/1742047/


All Articles