Constructors
A constructor sets up a new object with its starting values, all in one step.
What you will learn
- Write a constructor
- Create objects with starting values
- See why constructors are cleaner
Setting up objects the easy way
Last lesson we built an object, then set each field one line at a time. That is tedious and easy to forget. A constructor sets everything up the moment you create the object.
A constructor is a special method with the same name as the class and no return type. Java runs it automatically when you use new.
public class Dog {
String name;
int age;
// constructor: runs when you write new Dog(...)
Dog(String name, int age) {
this.name = name;
this.age = age;
}
void bark() {
System.out.println(name + " (" + age + ") says woof!");
}
}Note: Output: (No output yet — this defines the constructor. It will run automatically the moment we create a Dog with new, shown below.)
Creating objects in one line
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rex", 4);
Dog bella = new Dog("Bella", 2);
rex.bark();
bella.bark();
}
}Note: Output:
Rex (4) says woof!
Bella (2) says woof!
The values in new Dog("Rex", 4) flow straight into the constructor parameters, which use this to fill the fields. One clean line per object, with no risk of forgetting a field.
Why constructors are better
| Without a constructor | With a constructor |
|---|---|
| Many lines to set each field | One line creates a ready object |
| Easy to forget a field | All needed values are required up front |
| Object can exist half-empty | Object is valid from the start |
Tip: If you write no constructor, Java gives you a free empty one (the default constructor). The moment you write your own, that free one disappears — so add an empty one too if you still need new Dog().
Q. When does a constructor run?
new. It is the perfect place to set the object starting field values.✍️ Practice
- Add a constructor to your
Bookclass that setstitleandpages, then create a book in one line. - Create three different objects using the constructor and call a method on each.
🏠 Homework
- Write a
Studentclass with a constructor (name, grade) and a methodreport()that prints a one-line report. Create two students.