Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

New to Java...

I have a name class that has:

private String firstName;
private String middleInitial;
private String lastName;

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?

like image 482
iggy2012 Avatar asked Nov 30 '22 04:11

iggy2012


2 Answers

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.

like image 145
matt b Avatar answered Dec 01 '22 17:12

matt b


Well, two options:

  • Just have a constructor with three parameters, and call it using null or the empty string for middleInitial
  • Overload the constructors, possibly calling one from the other.

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)
{
    this(firstName, "", 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");

or

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.

like image 45
Jon Skeet Avatar answered Dec 01 '22 18:12

Jon Skeet