javaconstructorfieldparameterized-constructorclass-fields

Different ways to initialize object field with parameter


What other ways are there to initialize the class field "fieldList" based on a given List object? One way would be Parameterized constructor.

class ObjectA {
  private List<String> fieldList;

  // 1. Parameterized constructor
  public ObjectA(List<String> _fieldList) {
    this.fieldList = _fieldList;
  }
}

Solution

  • Another way can be via a setter method

    // 2. Setter method
    public void setFieldList(List<String> fieldList) {
        this.fieldList = fieldList;
    }