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?
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.
Well, two options:
middleInitial
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With