Course contentsShow
← Java
Lesson 329 of 2,8708. Classes and EncapsulationFree lesson

public: Universal Accessibility

Understand how public members are accessible from anywhere, and when to use public access appropriately.

public: Universal Accessibility

You'll learn when and why to make class members publicly accessible from anywhere in your program.

The Most Open Access Level

When you mark a class member (field, method, or constructor) with the public keyword, you're giving universal access—any code in any class, in any package, anywhere in your application can see and use it. There are no restrictions.

Think of public like a billboard on a highway: it's meant to be seen by everyone. If you want something to be part of your class's official interface—the way the outside world should interact with your object—make it public.

When to Use public

Use public for:

  • Methods that define your class's behavior that other classes need to call
  • Constructors that allow object creation from other packages
  • Classes themselves that need to be used across your application
public class BankAccount {
    private double balance;  // Hide internal state
    
    public BankAccount(double initialBalance) {  // Anyone can create accounts
        this.balance = initialBalance;
    }
    
    public void deposit(double amount) {  // Anyone can call this
        this.balance += amount;
    }
    
    public double getBalance() {  // Anyone can check balance
        return this.balance;
    }
}

Notice: the balance field is private (encapsulated), but the methods are public. This pattern is fundamental—hide the data, expose the operations.

When NOT to Use public

Don't make fields public unless they're constants. Public fields break encapsulation because external code can modify them directly, bypassing any validation logic.

Key Takeaway: Use public to define your class's external interface—the methods and constructors that other code should use—but keep implementation details private.