Constructors

Constructor headers
Backpacks in a store's inventory are described by this class.
public class Backpack
{
private double liters;
private String color;
public Backpack()
{
liters = 20.0;
color = "gray";
}
public Backpack(String shade, double size)
{
liters = size;
color = shade;
}
}
The two variables at the top hold each backpack's attributes, its capacity in liters and its color. Below them are two constructors, the code that runs when a backpack is created. A constructor's name is its class's name, and its header lists no return type at all, void included. Writing classes like this one comes later in the course, but reading their constructors starts here.
Signatures and overloading
A constructor's signature is the class name and its parameter types, in order. These two are Backpack() and Backpack(String, double). The second header's list gives each value's type and the name the body uses for it. Those names, shade and size, aren't part of the signature.
The two signatures differ, so the class can have both, and the constructors are overloaded. The first takes no arguments and makes a standard 20-liter gray backpack. The second takes the color and the size from the caller.
Which constructor runs
An object is created with new and a constructor call, and the arguments decide which constructor runs.
Backpack day = new Backpack();
Backpack hiking = new Backpack("green", 45.0);
The first call has no arguments, so it runs Backpack(), and day refers to a 20.0-liter gray backpack. The second call passes a String followed by a double, which matches the other constructor, and hiking refers to a 45.0-liter green one.
The arguments have to line up with one of the parameter lists, the same number of them in the same order. Since neither constructor takes a double first, new Backpack(45.0, "green") doesn't compile. An int argument is compatible with a double parameter, though, so new Backpack("red", 30) runs the second constructor with size equal to 30.0.
What happens during the call
When Java reaches new Backpack("green", 45.0), the statement it's in pauses. Java creates the backpack, and the constructor's statements run, storing 45.0 and "green" in its attributes. Then the paused statement resumes, and the new backpack's reference goes into hiking.
The parameter size is a new variable, and its first value is copied from the argument. If a program passes a variable, as in double want = 30.0; followed by new Backpack("red", want), the constructor gets the value 30.0 and has no way to change want itself.