Access Modifiers on Methods
What you'll learn: How method access modifiers shape what callers can see and use versus what remains hidden inside your class.
The Public API vs Internal Implementation
Just as you've controlled field visibility with access modifiers, you can (and should!) control method visibility. The methods you mark public form your class's public API—the official interface other code should use. Methods marked private are internal implementation details that help your class do its work but aren't meant for outside callers.
Think of a restaurant: the menu items are the public API (what customers can order), while the kitchen's prep techniques and helper recipes are private methods (customers don't call them directly).
How Access Levels Shape Your Class
When you declare a method with an access modifier, you're making a promise:
publicmethods: Anyone can call these—they're your class's advertised functionalityprivatemethods: Only code inside this same class can call these—helper logic, validation, internal calculations- Package-private methods (no modifier): Classes in the same package can call these—useful for closely related classes
protectedmethods: Your class, same-package classes, and subclasses can call these (you'll explore this with inheritance later)
By keeping implementation details private, you're free to change how your class works internally without breaking code that depends on your public methods. The public methods remain stable; the private helpers can evolve.
public class BankAccount {
private double balance;
public void deposit(double amount) { // Public API
if (isValidAmount(amount)) { // Calls private helper
balance += amount;
}
}
private boolean isValidAmount(double amount) { // Internal detail
return amount > 0;
}
}
Key Takeaway: Public methods define what your class promises to do; private methods define how it does it. Separate API from implementation for maintainable, flexible code.