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

  1. Make field private
  2. getBalance() returns the value
  3. setBalance(value) sets the value

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler