Access modifiers in Java with Example

In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier.

If we talk about access modifier, there are four types of access modifier.

  1. default
  2. private
  3. public
  4. protected

Access modifier restricts the access of data members, methods, class, and constructors.

Access modifiers in Java with Example

Access modifiers also specify the access level of classes, variable methods, and constructor.

default access modifier

When no modifier is specified for a class, method, or data member then Java compiler consider it as default modifier.

The class, data members or methods having default access modifier are accessible only within the same package.

Example

Output

In the given example, access modifier (Scope) of A and the given method disp() are default then both are accessible within the same package. We are using two different package core1 and core2 so this program will throw a compilation error.

Java Private access modifier

It is a class level modifier; in other words, the scope of private modifier is limited to the class only. Some essential points about private access modifier are:

  • Methods and private data members are only accessible within the class.
  • In Java, a class and interface cannot be declared as private.
  • If we declare a constructor as private, then we cannot create the object of that class from outside of the class.

Example

Output

In the given example, we are trying to access private data member n and private method disp() from outside the class. So it will lead to compilation error.

Java Private constructor

Example

Output

In the given an example, we have declared a constructor A() as private, so we cannot create the instance of class A. it will lead to a compilation error.

Java public access modifier

The public access modifier has the widest scope among all other modifiers. It can be accessed from everywhere. It is specified using the keyword “public.”

Example

Output

  • Try to use most restrictive access level that makes sense for a particular member therefore always Use private modifier unless you have a good reason not to.
  • Try to avoid public fields except for constants.

Java Protected access modifier

The “protected” keyword is used to specify the protected access modifier. It is accessible within the same package or outside the package through inheritance.

Output

Pin It on Pinterest

Share This