Core Java · interview question
In an e-commerce application, consider a Customer class that has public fields for id and name. What is a potential risk with this design?
Multiple choiceMediumchapter-3-curatedpremiumcore-javacode-reading-and-state-safety
Answer and explanation
Correct answer
B. Other classes can directly change the id and name, risking invalid state.
Why
When fields are public, other classes can modify them directly without any validation checks, potentially leading to invalid or inconsistent states. Encapsulation is violated, and the object's invariants could be compromised.
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?