Core Java · interview question
In an e-commerce app, you have a class Order with a method calculateTotal(). The method uses variables defined in the method body. What is a sign that some of these variables should become fields?
Multiple choiceHardchapter-2-curatedpremiumcore-javacode-reading-and-refactoring-to-objects
Answer and explanation
Correct answer
A. The variables represent the state of the order.
Why
If variables represent the state of the order, they should be fields rather than method-local variables. Fields help encapsulate the state of an object, making it easier to manage and understand.
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?