Skip to content
Sharp

Object-oriented programming · interview question

What is the purpose of using 'this' in the following constructor? public class Product { private double price; public Product(double price) { this.price = price; } }?

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

Correct answer

B. To assign the parameter to the instance field

Why

In this constructor, 'this.price' refers to the instance field, allowing the method to differentiate it from the parameter 'price'. Without 'this', the parameter would overshadow the instance field.

Test yourself on Object-oriented programming

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

Start free test
All Object-oriented programming questions →