Java constructor - optional argument in a subclass constructor

Viewed 442

The overall system here is a sort of library. I have a superclass called Person, with two constructors: one that takes a first and last name as separate Strings, and another that takes those parameters as well as an ArrayList for middle names - the idea being that some people have no middle name. In a subclass called Member, I want to have the option of creating a member object with or without middle names, by passing an empty ArrayList. My first thought was something like this:

if (middleNames.size() == 0) {
    super(firstName, lastName);
} else {
    super(firstName, middleNames, lastName);
}

But I have now realised that the super() constructor has to be the first statement in the subclass constructor. Hopefully you can see what I'm trying to do here - is there a good way to do it without writing two constructors in the Member class? There are several lines of code that I'd rather not repeat.

1 Answers

You could construct Member instances via a static factory method instead of constructor.

class Member extends Person {
    static Member create(String firstName, List<String> middleNames, String lastName) {
        if (middleNames.isEmpty()) {
            return new Member(firstName, lastName);
        }
        return new Member(firstName, middleNames, lastName);
    }

    private Member(String firstName, String lastName) {
        super(firstName, lastName);
    }

    private Member(String firstName, List<String> middleNames, String lastName) {
        super(firstName, middleNames, lastName);
    }
}
Related