5.2 Constructors
Enduring Understanding
Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.
Learning Objective
Define instance variables for the attributes to be initialized through the constructors of a class.
Essential Knowledge
An object’s state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This creates a “has-a” relationship between the object and its instance variables.
Constructors are used to set the initial state of an object, which should include initial values for all instance variables.
Constructor parameters are local variables to the constructor and provide data to initialize instance variables.
When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. In this way, the instance variable is not an alias of the original object, and methods are prevented from modifying the state of the original object.
When no constructor is written, Java provides a no-argument constructor, and the instance variables are set to default values.
Last updated
Was this helpful?