Interview Q&A / Object-Oriented Programming

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What are constructor injection and setter injection, and which should you prefer?

SHORT ANSWER

Constructor injection passes dependencies when the object is created, so it is never half-built. Setter injection sets them afterwards. Prefer the constructor for required dependencies and setters only for optional ones.

Explain it simply

Buying a scooter with petrol and a key included, versus buying one and then arranging fuel later. With constructor injection, the object arrives ready to use. With setters, someone may forget a step and use it before it is ready.

Example

java
class Billing {
    private final PaymentGateway gateway;        // required, can be final
    private Logger logger = new NoOpLogger();    // optional, has a safe default

    Billing(PaymentGateway gateway) {            // constructor injection
        this.gateway = Objects.requireNonNull(gateway);
    }
    void setLogger(Logger logger) {              // setter injection
        this.logger = logger;
    }
}

Billing b = new Billing(new UpiGateway());
b.setLogger(new FileLogger());

Constructor injection makes required dependencies visible in one place, supports final fields, and fails fast if something is missing. Too many constructor parameters, say more than four or five, hint that the class does too much.

What to say in the interview

"I use constructor injection for mandatory dependencies, so objects are always valid and immutable, and setter injection only for optional ones with sensible defaults. A long constructor is a hint to split the class."

Common mistakes

  • Using setters for everything and ending up with objects that can be used before they are ready.

#dependency-injection#java#design

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.