Skip to content
Sharp

Object-oriented programming · interview question

Consider an Order class that must always have a positive quantity. How should this invariant be enforced?

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

Correct answer

A. Use a setter method with validation.

Why

Using a setter method with validation ensures that any changes to the quantity are checked, maintaining the positive quantity invariant.

Test yourself on Object-oriented programming

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

Start free test
All Object-oriented programming questions →