AP® Computer Science A · Unit 3 · Topic 3.4
Constructors and Default Values
A constructor is a special method that runs once, when an object is created with new, to load starting values into that object's fields.
Every object needs a moment where it gets set up before anyone can use it. That moment is the constructor. It runs exactly once, at the instant new creates the object, and its whole job is to take the arguments you pass in and store them into the object's fields so the object starts life in a sensible state. Without that, you'd have an object with fields sitting empty, waiting to be filled in by hand after the fact, which invites bugs where someone forgets a step.
Mechanically, a constructor looks like a method named exactly after the class, with parameters but no return type at all. Inside the body, you typically assign each parameter to the matching field, often using this.fieldName = parameterName when the names match. If a constructor never touches a particular field, that field is not left undefined. Java fills it with a default automatically: 0 for int and double, false for boolean, and null for any object reference like a String. So a forgotten field doesn't crash the program, it just quietly holds a default value, which can itself cause bugs if you expected something else.
The missing return type trips people up because new Student(...) obviously hands back a Student. The resolution is that new does the returning, not the constructor. new allocates memory for the object, calls the constructor purely to initialize fields, then new itself returns the reference. That's also why constructors connect directly to the private fields and encapsulation ideas sitting right next to this topic: the constructor is usually the only piece of code trusted to set fields directly, before getters and setters take over.
Key terms
- constructor
- A special method, named after the class, that runs once when new creates an object, to set up its fields.
- default value
- The automatic starting value Java gives a field the constructor never assigns: 0, false, or null depending on type.
- this keyword
- A reference to the current object, used inside a constructor to distinguish a field from a same-named parameter.
- instance variable
- A field that belongs to each object individually, holding that object's own data such as name or age.
Watch it explained
- How it worksHow does a constructor take arguments and load them into the new object's fields?
- Worked exampleTrace new Student("Ana", 17) and find the value sitting in each field afterwards.
- How it worksHow do instance variables get default values when a constructor never touches them?
- Common mistakeWhy doesn't a constructor have a return type even though it produces an object?
Check yourself
End of topic.