I need to code this class in java. I thought of making a bunch of constructors but i dont think thats the best way to do it. Id like to know if java has some sort of optional parameters or attributes to make this simpler.
Asked
Active
Viewed 68 times
-2
-
As in to make some attributes not necessary without making a lot of constructors – Juan Rojas Oct 06 '20 at 21:06
-
Do you mean something like [varargs](https://www.baeldung.com/java-varargs)? – JustAnotherDeveloper Oct 06 '20 at 21:06
-
That would be a good solution, but Im not sure how to implement it with the given class – Juan Rojas Oct 06 '20 at 21:10
-
3You could write just one constructor and pass `null` for the attributes that you don't have a string for. – khelwood Oct 06 '20 at 21:21
-
1Does this answer your question? [Java optional parameters](https://stackoverflow.com/questions/965690/java-optional-parameters) – dnault Oct 06 '20 at 21:32
1 Answers
0
You can do it with one constructor with varargs, since all fields of your class are of type String
:
public class Address {
private String street;
private String city;
private String postalCode;
private String state;
private String country;
public Address(String... params) {
street = params[0];
city = params[1];
//etc. Just take care to pass the arguments in the order you are
//assigning them when you call the constructor. Also check the size
//of varargs first so you don't assign arguments that don't exist.
}
}
And then call it like so to set only the street and city:
Address adress = new Address("myStreet", "myCity");
An alternative is to have one constructor with all the arguments, and if you don't want to set a value, pass null
to the constructor in place of the corresponding parameter:
Address adress = new Address("myStreet", "myCity", null, null, null);

JustAnotherDeveloper
- 2,061
- 2
- 10
- 24
-
2You missed out a detail with the varargs version, which is checking the length of the received array to check how many elements were actually supplied. Otherwise if you don't provide all the elements expected you'd get an arrayindexoutofbounds exception. – khelwood Oct 06 '20 at 21:22
-
Nice man, this is what i looking for. You think it will work well with console inputs? I have to use the scanner function so the user can input their desired attributes. – Juan Rojas Oct 06 '20 at 21:46
-
@JuanRojas If this solves your problem, please accept the answer. How you get the values that you'll pass to the constructor doesn't matter, it can be with `Scanner` or in any other way. – JustAnotherDeveloper Oct 06 '20 at 21:49
-
Unfortunately, solutions like this require the user to remember the order of the attributes. I would suggest a combination of constructor for all the values and an empty constructor. Then use the builder model with the setters for selected attributes. – WJS Oct 07 '20 at 13:42