Writing Constructors
An object's own attributes are declared as instance variables. A camping store describes each tent it sells by its model name, how many people it sleeps, and its floor area.
public class Tent
{
private String model;
private int sleeps;
private double floorArea;
}
The type of each instance variable is part of the design. A model name is text, a number of sleepers is a whole number, and an area in square meters can have a fractional part. The values an object's instance variables hold at a given moment are its state.
Setting the state
public Tent(String name, int people, double width, double length)
{
model = name;
sleeps = people;
floorArea = width * length;
}
The first two statements copy a parameter into an instance variable. The third computes a value from two parameters and stores the result. A tent 2.1 meters wide and 2.5 meters long gets a floor area of about 5.25. A constructor should give every instance variable a value, and this one does.
Tent dome = new Tent("Ridge 4", 4, 2.1, 2.5);Arguments line up with parameters in order: the first argument goes to the first parameter, and so on. Each argument has to be compatible with its parameter's type. Two parameters of the same type, like
width and length, can be passed in the wrong order with no error. Here a swap happens to give the same area, but a class that stored the width and length separately would quietly describe the wrong tent.Two constructors
A class can have more than one constructor, provided no two have parameter lists that agree in number, type, and order. Some of the store's tents have square floors.
public Tent(String name, double side)
{
model = name;
sleeps = 2;
floorArea = side * side;
}
This one takes a name and a side length, and every square tent sleeps 2. Java picks the constructor that fits the arguments given, so
new Tent("Trail 2", 1.8) runs this one and gives a floor area of about 3.24, while new Tent("Ridge 4", 4, 2.1, 2.5) runs the other. A call that matches no constructor, such as new Tent(4), doesn't compile.