-1

So I have a list of employees.txt files. How do you create a constructor for the object of class employees? The employees object have to have a rank, id, age and name, all of which the information is stored in this .txt file. How do I create a constructor that displays all this information when an object is created. I'm using BlueJ to develop this. Thanks

  • Depends on the format of your text file but if it were csv you could have `public Employee (String fields)` and do the parsing of the csv in the ctor. `toString` would echo the values of those fields – g00se Sep 07 '21 at 09:28

1 Answers1

0

The better approach is to not include display-specific information in your object. That is, don't put the parser in the constructor. Instead, have a helper class that parses the input format and constructs an object for you. This keeps separation of your model (class) and the view (text representation), making it easier to support different formats or the addition of new fields in your Employee class.

public class Employee {
    private String name;
    private String rank;
    private int age;
    private String id;
    // more fields ...

    public Employee() {
        // initialize
    }

    // setter/getter methods for each field, as appropriate
}

public class EmployeeCSVReader {
    public static Employee fromCSVLine(String csvLine) {
        Employee result = new Employee();
        // parse fields, call setter methods against Employee
        return result;
    }
}
cschmack
  • 51
  • 1
  • 3