Java: Access Modifiers

access modifier

Access Modifiers in Java

Access modifiers are functionality that is used to set the accessibility or visibility of classes, interfaces, variables, methods, constructors, data members, and setter methods.

They help to restrict access to the members of the program. 

Java provides four types of access modifiers:

  • Public
  • Private
  • Protected
  • Default.

Public Access Modifier

  • When methods, variables, classes, and so on are declared public, then we can access them from anywhere.
  • The public access modifier has no scope restriction.
  • The public access modifier has the widest scope among all other access modifiers.
  • It can be accessed from within the class, outside the class, within the package, and outside the package.
package prep1; 
public class first 
{ 
public void display() 
    { 
        System.out.println("Hey there Prepsters"); 
    } 
} 
package prep2; 
import p1.*; 
class second 
{ 
    public static void main(String args[]) 
    { 
        first obj = new first; 
        obj.display(); 
    } 
}

Private Access Modifier

  • When variables and methods are declared as private, they cannot be accessed outside of the class. 
  • It can be only be accessed within a class.
  • Top-level classes or interfaces can not be declared as private because
    • private means “only visible within the enclosing class”.
    • protected means “only visible within the enclosing class and any subclasses”
Run

class Prepster {
    // private variable
    private String name;
}

public class Main {
    public static void main(String[] main){

        Prepster p = new Prepster();
        p.name = "Hey, Prepster";
    }
}

Protected Access Modifier

  • The protected access modifier is accessible within the package and outside the package but through inheritance only.
  • The protected access modifier can be applied to the data member, method, and constructor. It can’t be applied to the class.
  • It provides more accessibility than the default modifier.
package p1; 

public class A
{
protected void display()
{
System.out.println("Welcome to PrepInsta");
}
}


package p2;
import p1.*;

class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}

}

Default Access Modifier

  • If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default the default access modifier is considered.
  • The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package.
package p1; 


class Prepster
{
void display()
{
System.out.println("Welcome to Prepinsta");
}
}

package p2;
import p1.*;


class PrepInsta
{
public static void main(String args[])
{

Prepster obj = new Prepster();

obj.display();
}
}