Can a top-level class be private or protected in Java?

No, a top-level class in Java cannot be declared as private or protected. A top-level class can only have public or default (package-private) access. This restriction exists because private and protected access modifiers are intended for class members or nested classes, not for standalone top-level classes.

Key Points: • A top-level class can be declared only as public or default (no modifier). • public makes the class accessible from any package. • Default access restricts the class to the same package. • private and protected are not allowed for top-level classes and will cause a compilation error. • private and protected can be used with inner (nested) classes.

Example: A utility class that should be accessible only within its package can be declared with default access, while a service class intended for use across the application can be declared public.

Code Example:

// Valid Top-Level Class
public class Employee {
}

// Valid Top-Level Class
class Department {
}

// Invalid Top-Level Classes
private class Manager {
}

protected class Team {
}

Compilation Error: The above private and protected top-level classes will fail to compile because Java does not allow these access modifiers for top-level classes.

Interview Tip: A concise interview answer is:

"No, a top-level class cannot be private or protected in Java. It can only be public or default (package-private). Private and protected access modifiers are allowed only for members and nested classes, not for standalone top-level classes."