Bird
0
0

You are designing a BankAccount class with a private balance field. Which design correctly allows controlled access to balance?

hard📝 Application Q8 of 15
Java - Encapsulation
You are designing a BankAccount class with a private balance field. Which design correctly allows controlled access to balance?
AProvide public methods to deposit, withdraw, and get the balance, keeping <code>balance</code> private.
BMake <code>balance</code> public so other classes can modify it directly.
CProvide only a public setter method for <code>balance</code> without a getter.
DMake <code>balance</code> protected and access it directly from other classes.
Step-by-Step Solution
Solution:
  1. Step 1: Understand encapsulation

    Private fields should be accessed via controlled public methods.
  2. Step 2: Evaluate options

    Provide public methods to deposit, withdraw, and get the balance, keeping balance private. provides methods to safely modify and read balance, enforcing rules.
  3. Step 3: Problems with other options

    Public or protected fields allow uncontrolled access, risking data integrity.
  4. Final Answer:

    Provide public methods to deposit, withdraw, and get the balance, keeping balance private. -> Option A
  5. Quick Check:

    Encapsulation requires private fields and public methods [OK]
Quick Trick: Use private fields with public methods for control [OK]
Common Mistakes:
  • Making fields public for easy access
  • Providing setters without validation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes