Java Access Modifiers

The access modifiers in Java specifies the accessibility or visibility or scope of a field, methodconstructor, or class.
Java defines four access modifiers:
Following shows their accessibility,

  1. default (Same class, Same package)
  2. private (Same class)
  3. protected ( Same class, Same package, Subclasses)
  4. public ( Same class, Same package, Subclasses, Everyone)

1. default:

Default access modifiers mean, no modifiers is specified to the class, method or data-members. These parts where no access modifiers are specified that are having a default modifier are only accessible within the same package.

let us see an example:
In this example we created two packages ‘name’ and ‘mainPack’. ‘name’ package contains the default access modifiers class and method. Now if we import this package in the mainPack then we will get a compile-time error because the class ‘Names’ is only accessible within that package.


2. private:

It is specified using the private keyword.
Variables, Methods, and constructors that are declared private modifiers are only accessed within the declared class itself.
Any other package cannot access them.
Classes and Interfaces cannot be declared as private but can only be applied to inner classes.

In this example, a class named ‘Name’ contain a private method called ‘display()’ which cannot be accessed in another class Main, showing the error result.

Output:


3. protected:

Variables, methods, and constructors, which are declared protected using the keyword ‘protected’.
Protected data methods and members are only accessible by the classes of the same package and the subclasses present in any package.
Classes and Interfaces cannot be declared protected.

Let us see it in an example:
The two package Pack1 and pack2 are declared where pack1 contains the protected method ‘display()’ and is accessed in pack2 by importing pack1 in it. In this example, the protected method ‘display()’ declared in a class ‘Name’ is accessed by class Main.

Output:

Note:
Methods and fields cannot be declared protected in an Interface.


4. Public:

Declaring fields and methods or classes public means making it accessible everywhere in a program or in an application. a public entity can be accessed from class in a program. However, if the needs to access the public class from the different package then in order to access it that package must be imported first.

Let us see it in an example:
Two classes Mult and Main are created in for different packages, named pack1 and pack2. Mult class is declared public and its method ‘multTwoNumber’ is also declared public and so to access it in a ‘Main’ class its package must be imported that is pack1 is imported in Main.java.

Output: