Skip to content
Sharp

Core Java · interview question

In an e-commerce application, you have a class ShoppingCart that contains a method addProduct(Product product). The method directly modifies a List<Product> defined inside the method body. What is a better object-oriented design approach?

Multiple choiceMediumchapter-2-curatedpremiumcore-javacode-reading-and-refactoring-to-objects
Choose one answer
Answer and explanation

Correct answer

C. Define List<Product> as a private field in the ShoppingCart class.

Why

Defining List<Product> as a private field in the ShoppingCart class allows the list to be associated with each instance of ShoppingCart, maintaining encapsulation and making it easier to manage the cart's state across multiple method calls.

Test yourself on Core Java

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

Start free test
All Core Java questions →