Parameterized Constructors: Accepting Arguments
What you'll learn: How to create constructors that accept parameters to initialize object fields with specific values right when the object is created.
The Problem with Default Values
You've seen that constructors are special methods for object creation. But so far, constructors have been empty or simple. What if you want each new object to start with different values? You could create the object, then manually set each field—but there's a better way.
Creating Constructors with Parameters
A parameterized constructor accepts arguments, just like regular methods do. When you create an object with new, you pass values that the constructor uses to initialize the object's fields immediately.
Think of it like ordering a custom coffee: instead of getting a plain default cup and adding sugar/milk yourself afterward, you tell the barista exactly how you want it made from the start.
Syntax
public class Person {
String name;
int age;
// Parameterized constructor
public Person(String personName, int personAge) {
name = personName;
age = personAge;
}
}
Now when you create a Person, you must provide values:
Person alice = new Person("Alice", 30);
Person bob = new Person("Bob", 25);
Each object is initialized with its own specific values right away. No need to set fields separately afterward.
How It Works
When new Person("Alice", 30) executes:
- Java allocates memory for a new
Personobject on the heap - The constructor receives
"Alice"and30as arguments - These values are assigned to the object's
nameandagefields - The fully-initialized object reference is returned
Key Takeaway: Parameterized constructors let you pass initial values when creating objects, ensuring every new instance starts with the exact state you specify—cleaner and safer than setting fields manually afterward.