Skip to content
Sharp

Object-oriented programming · interview question

In an e-commerce application, which statement correctly initializes a field using 'this'? public class Order { private int quantity; public Order(int quantity) { // Line X } }?

Multiple choiceMediumchapter-2-curatedpremiumoopthis-keyword
java
public class Order {
  private int quantity;
  public Order(int quantity) {
    this.quantity = quantity;
  }
}
Choose one answer
Answer and explanation

Correct answer

A. This.quantity = quantity;

Why

The correct statement is 'this.quantity = quantity;'. It assigns the parameter 'quantity' to the field 'quantity' of the object, differentiating between the two.

Test yourself on Object-oriented programming

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

Start free test
All Object-oriented programming questions →