Encapsulation and private

encapsulation

Part of: Writing Classes

Hiding the Internals Encapsulation is the practice of bundling an object's data together with the methods that operate on it, while hiding the data from outside code. In Java this is enforced with access modifiers , mainly private and public. - private, visible only inside the same class. - public, visible everywhere. The standard pattern is private fields, public methods : lock the data down, then expose carefully chosen methods as the only doorway. Code outside BankAccount cannot write acct.balance = -1000000;. It must go through deposit and withdraw, which enforce the rules. Why Encapsulation Matters Making fields private gives three big benefits: - Validity : methods reject bad data, so the object never enters an impossible state. - Control : the class decides exactly what outsiders can do. - Flexibility : you can change how data is stored internally without breaking other code, as long as the public methods behave the same. A Broken Invariant Imagine balance were public. Any line anywhere could do acct.balance -= 99999; and overdraw the account. Encapsulation makes that impossible because the only way to reduce the balance is withdraw, which checks the funds first. The rule "b

Challenge: Safe Withdraw