Modifiers can be used for Class?

Modifiers can be used for Class?

In Java, the access modifiers that can be used for classes are:

  • 1. public
  • 2. default (no modifier)

Modifiers can be used for Class?

Public Class

  • Scope: A `public` class is accessible from any other class, regardless of the package.
  • Usage: To allow a class to be used widely across different packages.

Example
  ```java
  // File: com/example/MyPublicClass.java
  package com.example;

  public class MyPublicClass {
      // Class implementation
  }
  ```

2. Default (Package-Private) Class

  • Scope: A class with no access modifier (default or package-private) is accessible only within its own package.
  • Usage: To restrict the use of the class to within the same package, ensuring encapsulation and preventing usage from outside the package.

Example
```java
  // File: com/example/MyDefaultClass.java
  package com.example;

  class MyDefaultClass {
      // Class implementation
  }
  ```

Key Points

  • Top-Level Classes: Only `public` and default (no modifier) are allowed for top-level classes.
  • Nested Classes: If a class is a nested class (an inner class within another class), it can use all four access modifiers: `public`, `protected`, `default` (no modifier), and `private`.

Example of Nested Class with Various Modifiers
```java
// File: com/example/OuterClass.java
package com.example;

public class OuterClass {
    public class PublicInnerClass {
        // Public nested class
    }

    protected class ProtectedInnerClass {
        // Protected nested class
    }

    class DefaultInnerClass {
        // Default (package-private) nested class
    }

    private class PrivateInnerClass {
        // Private nested class
    }
}
```

Summary

For top-level classes, you can use only `public` and default (no modifier) access modifiers:

  • public: The class is accessible from any other class.
  • default: The class is accessible only within its own package.

Nested classes, however, can use all four access modifiers (`public`, `protected`, `default`, `private`), allowing for more granular control over their visibility and accessibility.

Homepage

Readmore