Menu
CoddyTech

Encapsulation

Lesson 33 of 48 in Coddy's Rust for Java Developers course.

Java private members are accessible according to class-level access rules, including nested-class relationships. Rust privacy follows modules. A public struct may have private fields, and code outside that module must use the exposed API. Code in the defining module can access those private fields, so put an invariant boundary in a module instead of assuming an impl block creates a Java-style class boundary.

The example exposes a small door API. Callers can construct it and ask whether it is locked, but cannot set the field directly from the parent module. The method names communicate operations, and the field representation can change without changing a caller. Encapsulation alone does not enforce an invariant: every public operation must preserve the promised state rules.

Java: complete program

class Main {
    static class Door {
        private boolean locked;
        void lock() { locked = true; }
        boolean isLocked() { return locked; }
    }
    public static void main(String[] args) {
        Door door = new Door();
        door.lock();
        System.out.println(door.isLocked());
    }
}

Rust: complete program

mod door {
    pub struct Door { locked: bool }
    impl Door {
        pub fn new() -> Self { Self { locked: false } }
        pub fn lock(&mut self) { self.locked = true; }
        pub fn is_locked(&self) -> bool { self.locked }
    }
}
fn main() {
    let mut door = door::Door::new();
    door.lock();
    println!("{}", door.is_locked());
}

Pitfall: pub struct Door does not make its fields public, and a private field is not automatically private to only its impl block.

challenge icon

Challenge

Easy

Implement wallet::Wallet with private balance. Wallet::new(balance: i32) -> Option<Wallet> rejects negative balances. balance(&self) -> i32 reads the balance. deposit(&mut self, amount: i32) -> bool rejects negative amounts and otherwise adds them. withdraw(&mut self, amount: i32) -> bool rejects negative amounts or amounts above the balance. Every rejected operation leaves state unchanged; zero is accepted. solve reads a nonnegative initial balance followed by command pairs d amount or w amount. Return each result as true:balance or false:balance on its own line, followed by balance:n. All values and intermediate balances fit i32.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, wallet.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod wallet;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
assert!(wallet::Wallet::new(-17).is_none());
let mut a = wallet::Wallet::new(43).unwrap(); let b = wallet::Wallet::new(6).unwrap();
assert!(!a.withdraw(44)); assert_eq!(a.balance(), 43);
assert!(!a.withdraw(-2)); assert!(!a.deposit(-8)); assert_eq!(a.balance(), 43);
assert!(a.withdraw(43)); assert!(a.withdraw(0)); assert_eq!(a.balance(), 0);
assert!(a.deposit(11)); assert!(a.deposit(0)); assert_eq!(a.balance(), 11);
assert_eq!(b.balance(), 6); assert!(a.withdraw(4)); assert_eq!(a.balance(), 7);
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Java Developers

Practice on your own: Online Rust compiler