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

Class-Level Access Modifiers Overview

Learn which access modifiers can be applied to top-level classes and what they control.

Class-Level Access Modifiers Overview

What you'll learn: You'll discover which access modifiers can be applied to top-level classes and what they control.

What Can Top-Level Classes Wear?

When you declare a class at the top level of a .java file (not nested inside another class), you have only two access modifier options: public or default (package-private, meaning no modifier at all). That's it—no private or protected for top-level classes.

Think of it like building entrances: you can either make your building accessible to the entire city (public) or only to people in your neighborhood (default/package-private). You wouldn't build a private or protected building that exists independently—those concepts only make sense in relation to something else.

The Two Options

public Classes

A public class can be accessed from any other class in any package, as long as it's on the classpath. The class name must match the filename: public class MyClass must be in MyClass.java. You can only have one public class per .java file.

Default (Package-Private) Classes

When you omit the access modifier entirely, the class has default access, meaning it's only visible to other classes within the same package. This is useful for helper classes that support your public API but shouldn't be exposed to the outside world. You can have multiple default classes in one .java file.

Why This Restriction?

Java's design keeps top-level classes simple: they're either meant for public consumption or internal package use. The private and protected modifiers only make sense for nested classes, where there's an enclosing class to hide from or inherit relationships to consider.

Key Takeaway: Top-level classes can only be public (visible everywhere) or default/package-private (visible only within the same package)—no private or protected allowed.