AnyCompiler

Encapsulation

Marking a field private prevents code outside the class from touching it directly — the class can then guarantee its own invariants, since the only way to change its state is through the methods it chooses to expose, like deposit below.

public class Main {
    static class BankAccount {
        private double balance;

        BankAccount(double initial) {
            balance = initial;
        }

        double getBalance() {
            return balance;
        }

        void deposit(double amount) {
            balance += amount;
        }
    }

    public static void main(String[] args) {
        BankAccount account = new BankAccount(100.0);
        account.deposit(50.0);
        System.out.println("Balance: " + account.getBalance());
    }
}
Output
Balance: 150.0

balance can never be set to an invalid value from outside BankAccount, because nothing outside the class can reach the field directly — every change has to go through deposit, which the class controls completely.

Next: inheritance — extends, super, and overriding a method with @Override.

Practice exercise

Define a class Temperature with a private double celsius, a constructor that sets it, and a method getFahrenheit() that returns celsius * 9.0 / 5.0 + 32.0. Create a Temperature with celsius 100.0 and print its Fahrenheit value.