Access Modifiers In Java

Java access modifiers are special words that specify the accessibility of classes, methods, or variables within a program. They play a crucial role in safeguarding data and managing the reach of the codebase. This section will delve into the concept of access modifiers and their role in regulating the exposure of classes, methods, and variables.

What are Access Modifiers in Java?

Access modifiers are special words that specify the level of visibility or availability of classes, methods, constructors, and variables. They determine the locations from which these elements can be reached, whether it be within the identical class, inside the matching package, or even from external packages. Through the use of access modifiers, we are able to manage and regulate the access permissions.

There are four types of access modifiers in Java:

  • public
  • private
  • protected
  • default

Let's delve into the specifics of each access modifier.

1. public Access Modifier

The reach of a public modifier is extensive, allowing access from various scopes such as within the class, outside the class, within the package, and even outside the package. This modifier boasts the broadest accessibility compared to other modifiers available.

Example

The provided illustration showcases the implementation of public access modifiers.

Example

//save by A.java    

package pack;  

public class A {  

public void msg() { System.out.println("Hello"); }  

}
Example

//save by Main.java    

package mypack;  

import pack.*;  

class Main {  

  public static void main (String args[]) {  

   A obj = new A();  

   obj.msg();  

  }  

}

Output:

2. private Access Modifier

The private modifier restricts access to only within the class where it is declared, preventing external access to it.

Example

Below is an illustration showcasing the implementation of private access modifiers.

Example

class A{  

private int data=40;  

private void msg(){System.out.println("Hello java");}  

}   

public class Main{  

 public static void main(String args[]){  

   A obj=new A();  

   System.out.println(obj.data);//Compile Time Error  

   obj.msg();//Compile Time Error  

   }  

}

Upon compiling the program above, it will display the subsequent compile-time error.

Example

Main.java:8: error: data has private access in A

   System.out.println(obj.data);//Compile Time Error  

                         ^

Main.java:9: error: msg() has private access in A

   obj.msg();//Compile Time Error  

      ^

2 errors

Role of Private Constructor

When a class constructor is set as private, it restricts the creation of class instances from external sources. This can be demonstrated with the following example:

Example

class A{  

private A(){}//private constructor  

void msg(){System.out.println("Hello java");}  

}  

public class Main{  

 public static void main(String args[]){  

   A obj=new A();//Compile Time Error  

 }  

}

Upon compiling the program provided above, the compiler will display the subsequent compile-time error.

Example

Main.java:7: error: A() has private access in A

   A obj=new A();//Compile Time Error  

         ^

1 error

Note: A class cannot be private or protected except nested class.

3. protected Access Modifier

The protected access modifier allows access within the package and from outside the package, but exclusively through inheritance. It can be used for data members, methods, and constructors, but not for classes. This modifier offers greater accessibility compared to the default modifier.

Example

The next illustration showcases how protected access modifiers are utilized.

Example

//save by A.java  

package pack;  

public class A {  

protected void msg() { System.out.println("Hello"); }  

}
Example

//save by Main.java  

package mypack;  

import pack.*;  

class Main extends A {  

  public static void main (String args[]) {  

   B obj = new B();  

   obj.msg();  

  }  

}

Output:

4. Default Access Modifier

If no specifier is specified, the default access specifier is automatically applied. The default modifier is limited to being accessed within the same package. External access is not permitted. It offers greater accessibility than private access, although it is more limiting compared to protected and public access levels.

Example

An illustration provided below showcases the utilization of default access modifiers.

Example

//save by A.java  

package pack;  

class A {  

  void msg() {System.out.println("Hello"); }  

}
Example

//save by Main.java  

package mypack;  

import pack.*;  

public class Main {  

  public static void main (String args[])   {  

   A obj = new A();//Compile Time Error  

   obj.msg();           //Compile Time Error  

  }  

}

Output:

Output

Compile Time Error

In the scenario described, the visibility of class A and its method msg is set to default, making them inaccessible from external packages. Compiling the program mentioned results in a compile-time error.

Access Modifiers with Method Overriding

The accessibility of methods in inheritance is influenced by access modifiers. In the scenario where a subclass overrides a method from its parent class, the overriding method is not allowed to have a stricter access modifier compared to the original method.

Rules

Follow the below given rules while using the access modifiers with the method overriding:

  • A method declared as public in the parent class must be public in the child class.
  • A method declared as protected in the parent class can be protected or public in the child class.
  • A method with default (no modifier) in the parent class can be default or protected or public in the child class, but not private .
  • A method declared as private in the parent class is not inherited , so it cannot be overridden.
  • Example

Below is an example showcasing how access specifiers work in conjunction with method overloading.

Example

class A {  

protected void msg() { System.out.println("Hello java"); }  

}  

public class Main extends A {  

void msg(){System.out.println("Hello java"); }             //C.T.Error  

 public static void main (String args[]) {  

   Main obj=new Main();  

   obj.msg();  

   }  

}

The default access modifier imposes greater restrictions compared to the protected modifier, leading to a compile-time error.

Accessibility or Scope of Java Access Modifiers

Displayed below is a table illustrating the accessibility levels of Java access modifiers:

Access Modifier Within Class Within Package Outside Package by Subclass Only Outside Package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

1. public

  • Accessible from anywhere (inside/outside the package).
  • Has the widest accessibility.
  • Used for methods and classes that need to be globally accessible.
  • 2. private

  • Strictly the most restrictive modifier.
  • Limits access only to within the same class.
  • Essential for encapsulation and protecting sensitive data.
  • Not accessible outside the class, even in the same package.
  • Private constructor prevents object creation outside the class.
  • 3. protected

  • Accessible within the same package.
  • Accessible outside the package, but only through inheritance.
  • More accessible than the default, but more restrictive than the public.
  • 4. default

  • When no modifier is specified.
  • Limited access only to other classes within the same package.
  • Cannot be accessed outside the package, even by subclasses.

Input Required

This code uses input(). Please provide values below: