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

Member-Level Access Modifiers: The Four Options

Review private, package-private, protected, and public for fields, methods, and constructors.

Member-Level Access Modifiers: The Four Options

What you'll learn: You'll understand the four access levels available for fields, methods, and constructors, and how they control visibility across your codebase.

The Four Access Levels

Unlike top-level classes (which only have public and package-private), class members—fields, methods, and constructors—can use all four access modifiers:

  1. private – Visible only within the same class
  2. Package-private (default) – Visible within the same package (no modifier keyword)
  3. protected – Visible within the same package AND to subclasses in other packages
  4. public – Visible everywhere

How They Work

Think of these as security clearance levels for your code:

  • private is like a personal diary—only you (the class) can read it
  • Package-private is like sharing with your immediate team (same package)
  • protected extends access to your "extended family" (subclasses)
  • public is broadcasting to the world
package com.example;

public class Account {
    private String accountId;           // Only Account can access
    double balance;                     // Package-private: any class in com.example
    protected String customerName;      // Same package + subclasses elsewhere
    public void deposit(double amount) { // Anyone, anywhere
        balance += amount;
    }
}

When to Use Each

  • private: Default choice for fields and helper methods—maximize encapsulation
  • Package-private: Implementation details shared within a module/package
  • protected: Designed for inheritance—letting subclasses access implementation
  • public: Your class's official API that external code depends on

Key Takeaway: All four access modifiers work on fields, methods, and constructors, giving you fine-grained control over encapsulation—from completely hidden (private) to fully exposed (public).