Object-oriented programming · interview question
Consider the following code: What is a flaw in using public getters and setters for the 'balance' field in a BankAccount class?
Multiple choiceHardchapter-3-curatedpremiumoopgetters-and-setters-design
public class BankAccount { private double balance; public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } }Answer and explanation
Correct answer
A. It allows unauthorized modification to the balance.
Why
Public getters and setters for the 'balance' field allow direct access and modification, bypassing any necessary validation or business logic that might ensure the account balance remains consistent and secure.
Test yourself on Object-oriented programming
A free test with instant, explained results. No account needed.
More Object-oriented programming questions
- Why does declaring a method as 'final' in a superclass change runtime behavior?
- Why might a developer choose to use a 'restock' method rather than a public setter for inventory?
- How do unmodifiable views differ from defensive copies in protecting internal collections?
- In an e-commerce application, what is the advantage of using a 'processOrder' method in a Product class?
- Which statement is true about interfaces in Java?
- Why are public mutable fields risky in a store model?