Core Java

core10Encapsulation

Path
pkg1core/core10Encapsulation.java
Package
pkg1core
Study order
11
Run
Single-file source launch
Command
java pkg1core/core10Encapsulation.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core10Encapsulation.java
1package pkg1core;2 3/*4 * core10Encapsulation.java5 * ------------------6 * Hiding internal state behind methods; validating via setters; immutability.7 *8 * EXPLANATION:9 *  - core10Encapsulation = bundling data + behavior and restricting direct access.10 *  - Make fields `private`; expose controlled getters/setters.11 *  - Benefits: invariants are protected, internals can change freely.12 */13public class core10Encapsulation {14 15    // A well-encapsulated mutable class with validation16    static class BankAccount {17        private double balance;                 // hidden state18        private final String owner;19 20        BankAccount(String owner, double opening) {21            if (opening < 0) throw new IllegalArgumentException("opening < 0");22            this.owner = owner;23            this.balance = opening;24        }25        public double getBalance() { return balance; }       // read-only access26        public String getOwner() { return owner; }27        public void deposit(double amt) {28            if (amt <= 0) throw new IllegalArgumentException("deposit must be > 0");29            balance += amt;                                   // invariant guarded30        }31        public void withdraw(double amt) {32            if (amt <= 0 || amt > balance) throw new IllegalArgumentException("invalid withdraw");33            balance -= amt;34        }35    }36 37    public static void main(String[] args) {38        BankAccount acct = new BankAccount("Alice", 100);39        acct.deposit(50);40        acct.withdraw(30);41        System.out.println(acct.getOwner() + " balance: " + acct.getBalance());42 43        try {44            acct.withdraw(1000);                 // blocked by validation45        } catch (IllegalArgumentException e) {46            System.out.println("Rejected: " + e.getMessage());47        }48        // We cannot do acct.balance = -999;  -> field is private (compile error)49    }50}