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
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.
More Core Java questions
- What does executing a throw statement inside a catch block evaluate to?
- In Java, what happens if an exception is thrown in a method and not caught within that method?
- Which method would you use to add an element to a List at a specific position?
- Consider the following code snippet. What is the issue with the 'applyDiscount' method?
- How do you correctly initialize a BigDecimal to represent the monetary value 50.75?
- Why might using == with Integer objects sometimes return false even if they have the same value?