Skip to content
Sharp

Object-oriented programming · interview question

How can immutability help in maintaining invariants within an object?

Multiple choiceHardchapter-3-curatedpremiumoopinvariants-and-validation
java
final class Order {
  private final int quantity;
  public Order(int quantity) {
    if (quantity <= 0) throw new IllegalArgumentException("Quantity must be positive");
    this.quantity = quantity;
  }
}
Choose one answer
Answer and explanation

Correct answer

B. By preventing any changes to the object's state after construction.

Why

Immutability ensures that once an object is constructed, its state cannot change, which inherently maintains invariants over the object's lifetime.

Test yourself on Object-oriented programming

A free test with instant, explained results. No account needed.

Start free test
All Object-oriented programming questions →