So I am currently working on a class that is supposed to be immutable.
package sysutilities;
public final class Address {
// Initializing fields/////////////////////////////////////////////////////
private final String street, city, state, zip;
//Constructor with 4 parameters - street, city, state and zip code/////////
public Address(String street, String city, String state, String zip) {
this.street = street.trim();
this.city = city.trim();
this.state = state.trim();
this.zip = zip.trim();
if (this.street == null || this.city == null || this.state == null ||
this.zip == null || !this.zip.matches("\\d+")) {
throw new IllegalArgumentException("Invalid Address Argument");
}
}
//Default Constructor//////////////////////////////////////////////////////
public Address() {
this.street = "8223 Paint Branch Dr.";
this.city = "College Park";
this.state = "MD";
this.zip = "20742";
}
//Copy Constructor/////////////////////////////////////////////////////////
public Address(Address inp) {
Address copyc = new Address();
}
My problem arises because a copy constructor can apparently not do its job if there are final private fields in the immediate vicinity. And so my code is giving me an error there. However, if I attempt to initialize the fields as null at the start, the rest of my program gives me an error.
Is there any way I can retain the immutability of the class without have private final fields?