-1

I need to avoid duplicate code with these constructors, so I wondered if there is a way to instantiate these variables only ones? I saw a lot of posts about chaining but I haven't gotten it to work properly.

class Trainingsschema
{
    // create an arrayList for every oefening
    private String klant;
    private String trainer;
    private Integer nummer;
    private ArrayList<Oefening> alleOefeningen;

    // two different constructors to correctly initialise the class variables
    public Trainingsschema(String klant, String trainer)
    {
        this.klant = klant;
        this.trainer = trainer;
        this.nummer = this.volgendUniekNummer();
        this.alleOefeningen = this.initialiseerOefeningen();
    }

    public Trainingsschema(String klant)
    {
        this.klant = klant;
        this.trainer = null;
        this.nummer = this.volgendUniekNummer();
        this.alleOefeningen = this.initialiseerOefeningen();
    }
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • *"I saw a lot of posts about chaining"* - That's how I'd do it. *"but I haven't gotten it to work properly"* - What did you try and what didn't work? – David Feb 11 '22 at 14:18

1 Answers1

2

You should have one constructor to initialize all the variables. Call it with defaults from other constructors, like this:

class Trainingsschema
{
    // create an arrayList for every oefening
    private String klant;
    private String trainer;
    private Integer nummer;
    private List<Oefening> alleOefeningen;

    // two different constructors to correctly initialise the class variables
    public Trainingsschema(String klant, String trainer)
    {
        this.klant = klant;
        this.trainer = trainer;
        this.nummer = this.volgendUniekNummer();
        // Show the method where you initialize the array.  Why do you need method?
        this.alleOefeningen = new ArrayList<>();
    }

    public Trainingsschema(String klant)
    {
        this(klant, null);
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561