Java Reference
In-Depth Information
2.5. Construction and Initialization
A newly created object is given an initial state. Fields can be initialized
with a value when they are declared, or you can accept their default
value, which is sometimes sufficient to ensure a correct initial state. But
often you need more than simple initialization to create the initial state.
For example, the creating code may need to supply initial data or per-
form operations that cannot be expressed as simple assignment.
2.5.1. Constructors
For purposes other than simple initialization, classes can have construct-
ors. Constructors are blocks of statements that can be used to initialize
an object before the reference to the object is returned by new . Construct-
ors have the same name as the class they initialize. Like methods, they
take zero or more arguments, but constructors are not methods and thus
have no return type. Arguments, if any, are provided between the par-
entheses that follow the type name when the object is created with new .
Constructors are invoked after the instance variables of a newly created
object of the class have been assigned their default initial values and
after their explicit initializers are executed.
This improved version of the Body class uses both constructors and initial-
izers to set up each new object's initial state:
class Body {
public long idNum;
public String name = "<unnamed>";
public Body orbits = null;
private static long nextID = 0;
Body() {
idNum = nextID++;
}
}
 
Search WWH ::




Custom Search