Object Creation and Storage
Topic 1.13: Instantiation
AP Computer Science A
Using Objects and Methods
Learning Objectives
1.13.A
Identify, using its signature, the correct constructor being called.
1.13.B
Develop code to declare variables of the correct types to hold object references.
1.13.C
Develop code to create an object by calling a constructor.
What is a Constructor?
Definition: A constructor is a special method used to create and initialize objects.
Key Characteristics:
- Has the same name as the class
- Called when an object is created using the new keyword
- No return type (not even void)
- Used to set initial values for object attributes
Constructor Signature
A constructor signature consists of:
- The constructor's name (same as class name)
- The ordered list of parameter types
Constructor Overloading
Constructors are overloaded when there are multiple constructors with different signatures.
Object References and Variables
A variable of a reference type holds an object reference or, if there is no object, null.
Declaring Reference Variables:
Creating Objects with new
An object is created using the new keyword followed by a call to one of the class's constructors.
Syntax:
Examples:
Constructor Parameters
Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
Example: Rectangle Class
Constructor Arguments
A constructor argument is a value that is passed into a constructor when the constructor is called.
Requirements:
- Arguments must be compatible in order and number with the parameter list
- Arguments are passed using call by value
- Call by value initializes parameters with copies of the arguments
Key Takeaways
Constructors
- Have the same name as the class
- Can be overloaded with different signatures
- Initialize object attributes
Object Creation
- Use the new keyword
- Reference variables hold object references or null
- Arguments are passed by value
Execution
- Constructor calls interrupt sequential flow
- Control returns after constructor completes