• In java access modifiers is the accessibility or scope of a field, method, constructor, or class.
  • The access specifiers are used to define how the variables and functions can be accessed outside the class.
  • We can change the access level of constructors, fields, methods, and class by applying the access modifier.
  • In C++ there are four types of access modifiers, they are:
    • Private
    • Public
    • Protected
    • Default

Private

  • The private modifier is only within the class and it cannot be accessed from outside the class.

Sample Code

class A{  

private int data=40;  

private void msg(){System.out.println("Welcome to Wikitechy");}  

}  

  

public class Simple{  

 public static void main(String args[]){  

   A obj=new A();  

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

   obj.msg();//Compile Time Error  

   }  

}  

Output

Public

  • The public modifier is everywhere, and it can access from within the class, outside the class, within the package and outside the package.

Sample Code

package pack;  

public class A{  

public void msg(){System.out.println("Welcome to Wikitechy");}  

}  

Output

Protected

  • The protected modifier is within the package and outside the package through child class.
  • It cannot be accessed from outside the package, if you do not make the child class.

Sample Code

package pack;  

public class A{  

protected void msg(){
System.out.println("Welcome to Wikitechy");
}  

}  

Output

Default

  • The default modifier is only within the package and it cannot be accessed from outside the package.
  • It will be the default, if you do not specify any access level.

Sample Code

package pack;  

class A{  

  void msg(){System.out.println("Welcome to Wikitechy");}  

Output

Categorized in: