Access Modifiers Allowed For Top Classes

Access Modifiers Allowed For Top Classes

In Java, access modifiers define the visibility and accessibility of classes, methods, and variables. For top-level classes (i.e., classes that are not nested within other classes), only two access modifiers are allowed:

1. Public

2. Package-Private (default, no modifier)

Access Modifiers Allowed For Top Classes

Allowed Access Modifiers for Top-Level Classes

1. Public

A public class is accessible from any other class in any package.

Example
```java 
  public class PublicClass {
      // class definition
  }
  ```

File Naming : If a class is declared public, the file name must match the class name (e.g., `PublicClass.java` for a public class named `PublicClass`).

2. Package-Private (Default)

A package-private class is only accessible within the same package. It is the default access level if no access modifier is specified.

Example
class PackagePrivateClass {
      // class definition
  }
  ```

Usage : No keyword is used for package-private; it is simply declared without an access modifier.

Example
```java 
// File: Example.java

// Public top-level class
public class Example {
    public static void main(String[] args) {
        System.out.println("This is a public class.");
        
        // Accessing a package-private class
        PackagePrivateClass ppc = new PackagePrivateClass();
        ppc.display();
    }
}

// Package-private (default) top-level class
class PackagePrivateClass {
    void display() {
        System.out.println("This is a package-private class.");
    }
}
```

Not Allowed Access Modifiers for Top-Level Classes

  • Protected: Cannot be used with top-level classes. It is only applicable to members within classes and interfaces.
  • Private : Cannot be used with top-level classes. It is only applicable to members within classes and interfaces.

Summary

For top-level classes in Java, only `public` and package-private (default, no modifier) access levels are allowed. A `public` class is accessible from any other class in any package, while a package-private class is only accessible within its own package. Access modifiers such as `protected` and `private` are not allowed for top-level classes.

Homepage

Readmore