Java Default Access Modifiers

www‮gi.‬iftidea.com

Java has four access modifiers: public, private, protected, and default (also known as package-private).

The default access modifier is used when no access modifier is specified. It has the following characteristics:

  • It is only accessible within the same package as the class or interface that it is defined in.
  • It is not accessible outside the package, even if the class that uses it is a subclass of the class it is defined in.
  • It is not visible to other packages and cannot be inherited by subclasses outside the package.

To define a class or interface with default access, you simply omit the access modifier keyword:

class MyClass {
  // default access
  int myVar;
  void myMethod() {
    // default access
  }
}

In the example above, the MyClass class and its members (the myVar field and the myMethod() method) are all using default access, which means they can only be accessed within the same package as MyClass.