Constructors in general
Constructors:
Note that a conventional distinction is made in Java between the
"default constructor"
and a "no-argument constructor":
-
the default constructor is the constructor provided by the system in the
absence of any constructor provided by the programmer. Once a programmer
supplies any constructor whatsoever, the default constructor is no longer
supplied.
-
a no-argument constructor, on the other hand, is a constructor provided
by the programmer which takes no arguments.
This distinction is necessary because the behavior of the two kinds of constructor are
unrelated: a default constructor has a fixed behavior defined by Java, while the
behavior of a no-argument constructor is defined by the application programmer.
Example
Resto is an immutable class, since
its state cannot change after construction. Note that:
-
all validation is performed in its constructor
-
almost all of its javadoc is concerned with stating precisely what is to
be passed to the constructor
import java.math.BigDecimal;
import java.util.Objects;
public final class Resto {
public Resto(
String id, String name, String location, BigDecimal price, String comment
) throws ModelCtorException {
this.id = id;
this.name = Objects.requireNonNull(name);
this.location = location;
this.price = price;
this.comment = comment;
validateState();
}
public String getId() { return id; }
public String getName() { return name; }
public String getLocation() { return location; }
public BigDecimal getPrice() { return price; }
public String getComment() { return comment; }
@Override public String toString(){
return id + ":" + name;
}
@Override public boolean equals(Object aThat) {
if (this == aThat) return true;
if (!(aThat instanceof Resto)) return false;
Resto that = (Resto)aThat;
for(int i = 0; i < this.getSigFields().length; ++i){
if (!Objects.equals(this.getSigFields()[i], that.getSigFields()[i])){
return false;
}
}
return true;
}
@Override public int hashCode(){
return Objects.hash(getSigFields());
}
private final String id;
private final String name;
private final String location;
private final BigDecimal price;
private final String comment;
private void validateState() throws ModelCtorException {
}
private Object[] getSigFields(){
return new Object[] {name, location, price, comment};
}
}
See Also :