Getters and Setters in Java: Explanation & Practice
Implement encapsulation with getters and setters
Problem summary
Create a BankAccount class with private balance and getter/setter methods.
Starter code
// Create BankAccount with:
// - private double balance
// - getter and setter for balance
public class Main {
public static void main(String[] args) {
// Create account, set balance to 1000, then print it
// Output: Balance: 1000.0
}
}Expected output and test cases
- Get balance
Balance: 1000.0
Hints
- Make field private
- getBalance() returns the value
- setBalance(value) sets the value
Related OOP Basics exercises
- Practice Create a Simple Class in Java
- Practice Using Constructors in Java
- Practice Static Members in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler