How to make constructor that takes in 2 if there are 2 parameters, or 3 if there are 3

as its instance variables. If I had certain data that had only firstName and lastName, no middleInitial, how would I make the constructor so that it took only 2 parameters instead of three?

asked Jul 20, 2011 at 18:49 41 1 1 gold badge 1 1 silver badge 2 2 bronze badges

9 Answers 9

You simply write a constructor with two parameters and a constructor with three

public YourClass(String firstName, String lastName) < . >public YourClass(String firstName, String middleInitial, String lastName)

Callers can then choose to use the appropriate constructor based on their needs.

answered Jul 20, 2011 at 18:51 140k 66 66 gold badges 284 284 silver badges 349 349 bronze badges

Well, two options:

As an example for the latter, using an empty string as the default middle initial:

public Person(String firstName, String middleInitial, String lastName) < this.firstName = firstName; this.middleInitial = middleInitial; this.lastName = lastName; >public Person(String firstName, String lastName)

However, the compiler will need to know which one you're calling from the call site. So you can do:

new Person("Jon", "L", "Skeet"); 
new Person("Jon", "Skeet"); 

. but you can't do:

// Invalid new Person(firstName, gotMiddleInitial ? middleInitial : . lastName); 

and expect the compiler to decide to use the "two name" variant instead.