Access Modifiers In Java – Tutorial With Examples

This video tutorial explains what are Access Modifiers in Java and how to use Default, Public, Protected and Private Access Modifiers with the help of examples:

In Java, we have classes and objects. These classes and objects are contained in a package. Besides, classes can have nested classes, methods, variables, etc. As Java is an object-oriented programming language, we have to follow the encapsulation wherein we hide the unwanted details.

Java provides entities called “Access Modifiers or access specifiers” that help us to restrict the scope or visibility of a package, class, constructor, methods, variables, or other data members. These access modifiers are also called “Visibility Specifiers”.

By using the access specifiers, a particular class method or variable can be restricted to access or hidden from the other classes.

=> Check ALL Java Tutorials Here.

Access Modifiers in Java

Video Tutorial On Access Modifiers In Java

Access Modifiers In Java

The access specifiers also determine which data members (methods or fields) of a class can be accessed by other data members of classes or packages etc. To ensure encapsulation and reusability, these access specifiers/modifiers are an integral part of object-oriented programming.

Modifiers in Java are of two types:

#1) Access Modifiers

Access modifiers in Java allow us to set the scope or accessibility or visibility of a data member be it a field, constructor, class, or method.

#2) Non-access Modifiers

Java also provides non-access specifiers that are used with classes, variables, methods, constructors, etc. The non-access specifiers/modifiers define the behavior of the entities to the JVM.

Some of the non-access specifiers/modifiers in Java are:

  • static
  • final
  • abstract
  • transient
  • volatile
  • synchronized
  • native

We have covered static, synchronized, and volatile keywords in our earlier tutorials. We will cover the other non-access modifiers in our future tutorials as they are beyond the scope of this tutorial.

Types Of Access Modifiers In Java

Java provides four types of access specifiers that we can use with classes and other entities.

These are:

#1) Default: Whenever a specific access level is not specified, then it is assumed to be ‘default’. The scope of the default level is within the package.

#2) Public: This is the most common access level and whenever the public access specifier is used with an entity, that particular entity is accessible throughout from within or outside the class, within or outside the package, etc.

#3) Protected: The protected access level has a scope that is within the package. A protected entity is also accessible outside the package through inherited class or child class.

#4) Private: When an entity is private, then this entity cannot be accessed outside the class. A private entity can only be accessible from within the class.

We can summarize the access modifiers in the following table.

Access SpecifierInside ClassInside PackageOutside package subclassOutside package
PrivateYesNoNoNo
DefaultYesYesNoNo
ProtectedYesYesYesNo
PublicYesYesYesYes

Next, we will discuss each of these access specifiers in detail.

Default Access Specifiers

A default access modifier in Java has no specific keyword. Whenever the access modifier is not specified, then it is assumed to be the default. The entities like classes, methods, and variables can have a default access.

A default class is accessible inside the package but it is not accessible from outside the package i.e. all the classes inside the package in which the default class is defined can access this class.

Similarly a default method or variable is also accessible inside the package in which they are defined and not outside the package.

The below program demonstrates the Default Access Modifier in Java.

class BaseClass 
{ 
    void display()      //no access modifier indicates default modifier
       { 
           System.out.println("BaseClass::Display with 'dafault' scope"); 
       } 
} 

class Main
{ 
    public static void main(String args[]) 
       {   
          //access class with default scope
          BaseClass obj = new BaseClass(); 
  
          obj.display();    //access class method with default scope
       } 
}

Output:

Default Access Modifiers In Java

In the above program, we have a class and a method inside it without any access modifier. Hence both the class and method display has default access. Then we see that in the method, we can directly create an object of the class and call the method.

Public Access Modifier 

A class or a method or a data field specified as ‘public’ is accessible from any class or package in the Java program. The public entity is accessible within the package as well as outside the package. In general, public access modifier is a modifier that does not restrict the entity at all.

class A 
{ 
   public void display() 
      { 
          System.out.println("SoftwareTestingHelp!!"); 
      } 
} 
class Main 
{ 
    public static void main(String args[]) 
      { 
          A obj = new A (); 
          obj.display(); 
      } 
}

Output:

Public access modifier in Java

Protected Access Specifier 

The protected access specifier allows access to entities through subclasses of the class in which the entity is declared. It doesn’t matter whether the class is in the same package or different package, but as long as the class that is trying to access a protected entity is a subclass of this class, the entity is accessible.

Note that a class and an interface cannot be protected i.e. we cannot apply protected modifiers to classes and interfaces.

The protected access modifier is usually used in parent-child relationships.

The below program demonstrates the usage of the Protected Access modifier in Java.

//A->B->C = class hierarchy
class A 
{ 
   protected void display() 
    { 
        System.out.println("SoftwareTestingHelp"); 
    } 
} 

class B extends A {}  
class C extends B {}

class Main{
     public static void main(String args[]) 
   {   
       B obj = new B();     //create object of class B   
       obj.display();       //access class A protected method using obj
       C cObj = new C();    //create object of class C
       cObj.display ();     //access class A protected method using cObj
   }   
}

Output:

Protected access modifier in Java

Private Access Modifier 

The ‘private’ access modifier is the one that has the lowest accessibility level. The methods and fields that are declared as private are not accessible outside the class. They are accessible only within the class which has these private entities as its members.

Note that the private entities are not even visible to the subclasses of the class. A private access modifier ensures encapsulation in Java.

Some points to be noted regarding the Private Access Modifier.

  1. Private access modifier cannot be used for classes and interfaces.
  2. The scope of private entities (methods and variables) is limited to the class in which they are declared.
  3. A class with a private constructor cannot create an object of the class from any other place like the main method. (More details on private constructors has been explained in our earlier tutorial).

The below Java program uses a Private Access Modifier.

class TestClass{  
    //private variable and method
    private int num=100;  
    private void printMessage(){System.out.println("Hello java");}  
    
}  
  
public class Main{  
 public static void main(String args[]){  
   TestClass obj=new TestClass();  
   System.out.println(obj.num);//try to access private data member - Compile Time Error  
   obj.printMessage();//Accessing private method - Compile Time Error  
   }  
}  

Output:

Private access modifier in Java

The program above gives compilation error as we are trying to access private data members using the class object.

But there is a method to access private member variables. This method is using getters and setters in Java. So we provide a public get method in the same class in which private variable is declared so that getter can read the value of the private variable.

Similarly, we provide a public setter method that allows us to set a value for the private variable.

The following Java program demonstrates the use of getter and setter methods for private variables in Java.

class DataClass {
    private String strname;    

// getter method
    public String getName() {
        return this.strname;
    }
    // setter method
    public void setName(String name) {
        this.strname= name;
    }
}
public class Main {
    public static void main(String[] main){
        DataClass d = new DataClass();       

 // access the private variable using the getter and setter
        d.setName("Java Programming");
        System.out.println(d.getName());
    }
}

Output:

a private string variable

The above program has a class with a private string variable. We provide a public getName member method that returns the value of the private variable. We also provide a public setName method in the class that takes a String as an argument and assigns it to the private variable.

As both methods are public, we can easily access them using the object of the class. This way we can overcome the compilation error that pops up every time when we try to access the private data members of the class.

Frequently Asked Questions

Q #1) How many Access Modifiers are there in Java?

Answer: Java provides four modifiers i.e. default, public, protected, and private.

Q #2) What are Access Modifiers and Non- Access Modifiers in Java?

Answer: Access modifiers define the visibility or scope of a program entity like a class or a method or a variable or a constructor. Non-access modifiers define the behavior of an entity. For example, a synchronized method or block indicates that it can operate in a multithreading environment, a final variable indicates that it is a constant.

Q #3) Why are Access Specifiers important?

Answer: Modifiers specify which class can access which other classes or methods or variables. Using access specifiers we can limit the access of various classes, methods, constructors, and variables and also ensure encapsulation and reusability of Java entities.

Q #4) Which Modifiers are not used for the class?

Answer: Protected and Private modifiers are not used for a class.

Q #5) What are Non-access Modifiers?

Answer: Modifiers that define the behavior of entities like class, method, or variables with which they are associated are non-access modifiers. As the name suggests they do not specify the access. Java provides various non-access modifiers like static, final, synchronized, volatile, abstract, etc.

More On Visibility Modifiers

Java provides many modifiers to access the variable, methods, and constructors.

There are 4 types of access variables in Java:

  1. Private
  2. Public
  3. Default
  4. Protected

#1) Private

If a variable is declared as private, then it can be accessed within the class. This variable won’t be available outside the class. So, the outside members cannot access the private members.

Note: Classes and interfaces cannot be private.

#2) Public

Methods/variables with public modifiers can be accessed by all the other classes in the project.

#3) Protected

If a variable is declared as protected, then it can be accessed within the same package classes and sub-class of any other packages.

Note: Protected access modifier cannot be used for class and interfaces.

#4) Default Access Modifier

If a variable/method is defined without any access modifier keyword, then that will have a default modifier access.

Access ModifiersVisibility
Public Visible to All classes.
ProtectedVisible to classes with in the package and the subclasses of other package.
No Access Modifier (Default)Visible to the classes with the package
privateVisible with in the class. It is not accessible outside the class.

Demo Class:

 class AccessModifiersDemo {

private int empsalaray ;
public String empName;

private void calculateSalary() {
System.out.println("insid methodone");
}

public String printEmpName(String empName ) {
this.empName=empName;
return empName;
}
} 

Java Access Modifiers demo

Accessing the members of the class in another class:

 public class TestAccessModifier {

public static void main(String[] args) {
AccessModifiersDemo accessobj =new
AccessModifiersDemo();

accessobj.calculateSalary();
}
} 

Access Modifiers Test

Output:

Accessing the members of the class in another class- output

Accessing the public members:

 public class TestAccessModifier {

          public static void main(String[] args) {
                        AccessModifiersDemo accessobj =new AccessModifiersDemo();


                        System.out.println(accessobj.printEmpName("Bobby"));

            }

} 

Output:

Bobby

Important Points:

  • Access specifiers define the visibility of the class.
  • If no keyword is mentioned then that is default access modifier.
  • Four modifiers in Java include public, private, protected and default.
  • Private and Protected keywords cannot be used for classes and interfaces.

Conclusion

In this tutorial, we explored Access Modifiers in Java in detail. Java provides four types of access modifiers or visibility specifiers i.e. default, public, private, and protected. The default modifier does not have any keyword associated with it.

When a class or method or variable does not have an access specifier associated with it, we assume it is having default access. Public access modifier allows access to everything whether inside or outside the class or package. There is no limit on access in the case of the public modifier.

Protected visibility specifier allows access only to subclasses inheriting the class in which protected members are declared. Private access modifier allows the least accessibility with the private data members to be accessible only within the class.

Modifiers limit the scope of data members like classes, constructors, methods, and variables and define the limit as to which classes or packages can access them. Access specifiers encourage encapsulation and reusability in Java. Note that classes and interface cannot be protected or private.

=> Visit Here To Learn Java From Scratch.