Java Access Modifiers

Access modifiers are used to set access levels for variables, methods, constructors and classes. A special keyword is used for each access modifier except the default. Default access modifier has no keyword. There are following type of access modifiers in java.

  • default
  • public
  • private
  • protected

In java there are some non-access modifiers which are static, synchronized, abstract, native, volatile, transient etc.

Default Access Modifier

The default access modifier is not explicitly declared for a class, variable or method. Any method or variable without any access modifier is accessible in any class in same package.

String chapter= “5”;

int countPages() {
/*some code here*/

Public Access Modifier

The public access modifier is declared with public keyword and it is accessible everywhere.

public class HelloWorld{

public void msg(){
System.out.println(“Hello World”);


Private Access Modifier

Any variable, method or constructor declared with private access modifier can be accessed only in that class in which it is defined. it is the most restrictive access modifier. We cannot declare class and interfaces with private access modifier in java.

public class Car {

private int carMake;

public String getCarMake() {
return this.carMake;
public void setCarMake(String carMake) {
this.carMake = carMake;


Protected Access Modifier

Any variable, method or constructor declared with protected access modifier can only be access in sub-classes within package or any other package through inheritance. Class and interface cannot be declared protected also methods and variables in an interface cannot be declared protected.

public class HelloWorld{

protected void msg(){
System.out.println(“Hello World”);


Leave a Reply

Your email address will not be published. Required fields are marked *