Well, two options:
- Just create a constructor with three parameters and call it using null or an empty string for
middleInitial - Overload the constructors, perhaps by calling them from one another.
As an example, the last one uses an empty string as the initial default average:
public Person(String firstName, String middleInitial, String lastName) { this.firstName = firstName; this.middleInitial = middleInitial; this.lastName = lastName; } public Person(String firstName, String lastName) { this(firstName, "", lastName); }
However, the compiler will need to know which one you are calling from the call site. So you can do:
new Person("Jon", "L", "Skeet");
or
new Person("Jon", "Skeet");
... but you cannot do:
// Invalid new Person(firstName, gotMiddleInitial ? middleInitial : ???, lastName);
and expect the compiler to decide to use the two-name option.
source share