Bird
0
0

How should you implement a BankAccount class to ensure the balance cannot be set to a negative value and can only be read externally?

hard📝 Application Q8 of 15
Java - Encapsulation

How should you implement a BankAccount class to ensure the balance cannot be set to a negative value and can only be read externally?

AMake balance private with no getter or setter methods.
BMake balance public and allow direct access to modify it.
CMake balance private, provide a getter, and a setter that validates non-negative values.
DMake balance protected and allow subclasses to modify it freely.
Step-by-Step Solution
Solution:
  1. Step 1: Protect balance variable

    Balance should be private to prevent direct external modification.
  2. Step 2: Provide controlled access

    A public getter allows reading the balance.
  3. Step 3: Validate in setter

    The setter should check that the new balance is not negative before setting.
  4. Final Answer:

    Make balance private, provide a getter, and a setter that validates non-negative values. -> Option C
  5. Quick Check:

    Private variable + validated setter + getter [OK]
Quick Trick: Private balance with validated setter and getter [OK]
Common Mistakes:
  • Making balance public allows invalid values
  • No setter means balance can't be updated
  • Protected allows uncontrolled subclass access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes