Course contentsShow
← Java
Lesson 702 of 2,87017. Access Control in DepthFree lesson

public Members: Unrestricted Access

Explore public members accessible from anywhere, forming the class's public API.

public Members: Unrestricted Access

What you'll learn: How public members create your class's external interface, accessible from anywhere in your codebase.

What public Means

When you declare a field, method, or constructor as public, you're saying "anyone can use this, no restrictions." Unlike private (class-only), package-private (package-only), or protected (package + subclasses), public removes all barriers. Any code in any package can access a public member, as long as it can access the class itself.

The Public API Concept

Think of public members as the front door of your class—the official way the outside world should interact with it. These members form your class's public API (Application Programming Interface). They're your contract with other developers: "Here's what you can rely on."

package com.example.model;

public class BankAccount {
    private double balance;  // hidden implementation
    
    // Public API methods
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    
    public double getBalance() {
        return balance;
    }
}
package com.example.app;

import com.example.model.BankAccount;

public class BankingApp {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.deposit(100.0);  // ✓ works from different package
        System.out.println(account.getBalance());  // ✓ accessible
    }
}

Use Public Sparingly

Every public member is a commitment. Changing or removing it later can break other code across your entire project. Expose only what's necessary; keep implementation details private or package-private.

Key Takeaway: public members are accessible from anywhere and define your class's external interface—use them intentionally to create a clear, stable API.