Skip to content

Constructors

A constructor is a block of code that runs when you create an object with new ClassName(...). It has the same name as the class and no return type.

Stage 1intro1 min read

What is a constructor?

A new object needs its starting values, or it is half built. A constructor is a special block of code that sets up a new object. It has the same name as the class, has no return type (not even void), and runs automatically when you write new ClassName(...).

Think of it as the object’s setup checkpoint. It collects what the object needs, rejects bad input, and leaves the new object ready to use.

Types you’ll see

  1. No-argument constructor: takes no parameters. If you write no constructor at all, Java adds a default constructor with no arguments for you. Once you write any constructor, Java stops adding that default. You can still write your own no-argument one.
  2. Parameterized constructor: takes arguments, for example public NotificationService(NotificationChannel channel). Callers use it to pass in dependencies or starting values.
  3. Private constructor: stops code outside the class from doing new MyClass(). Used in Singleton (only one instance is allowed) and in Builder (only the builder can create the object).

Example

// Parameterized: dependency injected from outside (DIP)
public class NotificationService {
    private NotificationChannel notificationChannel;

    public NotificationService(NotificationChannel channel) {
        this.notificationChannel = channel;
    }

    public void notify(String msg) {
        notificationChannel.send(msg);
    }
}
// Private constructor: no one can do 'new JudgeAnalytics()'
public class JudgeAnalytics {
    private static JudgeAnalytics instance;

    private JudgeAnalytics() {
        // Setup once
    }

    public static JudgeAnalytics getInstance() {
        if (instance == null) {
            instance = new JudgeAnalytics();
        }
        return instance;
    }
}
  • First: the constructor injects the NotificationChannel. The caller passes it in, so the class does not create it. This is dependency injection.
  • Second: the constructor is private, so only code inside the class can call it. getInstance() calls it once, the first time it is needed, and then returns that same object every time (Singleton).

Where you see it in this repo

  • DIP GoodCode: NotificationService(NotificationChannel channel) uses constructor injection.
  • Singleton: JudgeAnalytics() is private; object created only inside getInstance().
  • Builder: BurgerMeal(BurgerMealWithBuilder builder) is private; only the static nested builder class calls it via build().
  • Most classes: Parameterized constructors to set amount, cardNo, channelName, etc.

In this topic

Done with this topic?

How well do you know it?

PreviousEncapsulation