AP Computer Science A · Unit 1: Using Objects & Methods
1.7 Constructors
What is a constructor?
A constructor is a special method used to build and initialize a new object from a class. It has the same name as the class, no return type (not even void), and runs automatically when you use the new keyword. Its job is to set instance variables to starting values.
Default vs. parameterized constructors
If a class has no constructor written, Java provides a default constructor that sets fields to default values (0, null, false). A parameterized constructor accepts arguments so you can set specific starting values, like `new Dog("Rex", 3)`. Classes can have multiple constructors with different parameter lists (overloading).
Using this in constructors
Inside a constructor, this refers to the current object being created. It's used to distinguish instance variables from parameters with the same name, e.g., `this.age = age;`. Without `this`, the parameter would just reassign itself, leaving the instance variable unset.
Key terms
- Constructor
- A special method matching the class name, with no return type, used to initialize a new object's instance variables.
- Default constructor
- A no-argument constructor automatically provided by Java if no constructor is written; sets fields to default values.
- Parameterized constructor
- A constructor that takes arguments, letting you set specific initial values for an object's fields.
- this keyword (in constructors)
- Refers to the current object; used to distinguish instance variables from parameters of the same name (e.g., this.age = age).
- Constructor overloading
- Defining multiple constructors in a class with different parameter lists to allow different ways of creating objects.
Try an AP-style question
Which is true about constructors?
- They must always be named init
- They can only be declared private
- They return the type of the object
- Same name as the class, no return type
Show the answer
D. Special method.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 1.7 free in APrep