Skip to content
Sharp

Object-oriented programming · interview question

Consider the following code snippet. What is the issue with the constructor?

Multiple choiceMediumchapter-2-curatedpremiumoopconstructors
java
class Product {
  String name;
  double price;
  String category;

  Product(String name, double price) {
    this.name = name;
    this.price = price;
  }
}
Choose one answer
Answer and explanation

Correct answer

B. The constructor does not initialize all fields.

Why

In this code, the 'category' field is not initialized in the constructor, which could lead to unexpected behavior when the object is used.

Test yourself on Object-oriented programming

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

Start free test
All Object-oriented programming questions →