Object-Oriented JavaCore· 30 min read

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.

A class with a constructor
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

Build fully set-up objects in a single line each
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 constructorWith a constructor
Many lines to set each fieldOne line creates a ready object
Easy to forget a fieldAll needed values are required up front
Object can exist half-emptyObject 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?

Answer: A constructor runs automatically as the object is created with new. It is the perfect place to set the object starting field values.

✍️ Practice

  1. Add a constructor to your Book class that sets title and pages, then create a book in one line.
  2. Create three different objects using the constructor and call a method on each.

🏠 Homework

  1. Write a Student class with a constructor (name, grade) and a method report() that prints a one-line report. Create two students.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →