Scientech Easy Access Specifiers in Java | Example & Programs | Scientech Easy

Sunday, December 23, 2018

Access Specifiers in Java | Example & Programs

In a Java program, the functionality of the class, field, method, and constructor can be protected from other parts of the program by the presence or the absence of specifiers or modifiers. In this tutorial, we will learn one of the most important and basic topic Access Specifiers or modifiers in Java in a simple way and step by step.

Modifier in Java

A modifier is a keyword that you add to those definitions to change their meaning. In other words, It limits the visibility of the class, field, constructor or method in the Java program. Java language provides a  wide variety of modifiers but in this tutorial, we will learn two types of modifiers in Java. 
1. Access Modifiers
2. Non-access Modifiers.

Access Specifiers in Java

Access modifiers /specifiers define the boundary for accessing the class, variable, methods, or constructor. In other words, access modifiers are the modifiers which are used to restrict the visibility of classes, fields, method, and constructors. The access specifiers are also known as visibility modifiers. Java provides four explicit access modifiers: private, default, protected, and public. Each of these shall be described below.

Java supports four types of access modifiers.

Access specifiers in Java with example programs

1. Private
➲ Private access specifier can apply to a variable, method, constructor, inner class but not the outer class that is class itself.
➲ The instance variable can be private but a local variable cannot be private.
➲ Private members (field, method or constructor) cannot be accessed outside the class. They are accessible only within the class.
➲ Private members cannot be inherited to the subclass and therefore not accessible in subclasses.
➲ If we make any constructor as a private, we cannot create the object of that class from other class and also cannot create the subclass of that class.
➲ A class cannot be private except for inner classes. Inner classes are the members of the outer class. so members of the class can be private.
➲ If we declare a method as private, it behaves like a method declared as final. We cannot call the private method from outside the class.
Let's understand these points by taking a very simple example.
In this example we create two classes class A and class B. Class A contains a private field and private method. When we will access this private field and private method from outside the class B, then they will give compile time error.
Program source code 1:
    package scientecheasy; class A { // Declaration of Instance Variable. private int data=30; // Here instance variable is private. private void msg() // Here method is also private. { System.out.println("Hello Java, this is my first java programe"); } }
Now create another class B and call private field and method of class A.
    class B { // Main method public static void main(String[] args) { //Create the object of class A and call members of class A using reference variable 'a'. A a=new A(); // a is a reference variable. System.out.println(a.data): // Compile time error will occur because we cannot call private members of any class from outside the class. a.msg(); // Compile time error. So we cannot call the private method of any class because this is accessible within the class only. } }

Role of Private Constructor

If you declare any constructor of a class as a private then you cannot create the object of the class from outside the class. In other words, we cannot create the subclass of that class. For example.
Program source code 2:
    class A { // Declaration of Constructor. private A() // Here Constructor is declared as private. { System.out.println("Constructor is private"); } // Declaration of instance method. private void msg() // Method is private. { System.out.println("Method is private"); } }
Now create another class B and call class A. As you will call the class A, it will give compile time error.
    class B{ // Main method. public static void main(String args[]) { // Create the object of class A. A a=new A(); // Compile time error. because the constructor is private and we cannot create the object of class A from outside the class. } }
Q. Can you find the error in the code?
       private class Student{
          private int roll=4;
             private class Name{
                // Inner class 
                                         }
                                  }
Ans:- Outer class cannot be private but inner class can be private. Instance variable can be private.

2. Default(Package access modifier)
➲ When access specifier is not specified to members of a class, it is called default access specifier.
➲ Default members are accessed or visible inside of the class and everywhere within classes in the same package or folder only. They can not be accessed outside the package.
➲ The default can apply to the instance variable, local variable, constructor, methods, inner class or outer class.
➲ Default members can be inherited to the subclass within the same package only. It cannot be inherited from outside the package.

 Let's understand with a simple example
 We have created two packages pack1 and  pack2. we are accessing the class A from outside its package since class A is default i.e not public. Therefore it cannot be accessed from outside the package.
Program source code 3:
    // Save by Student.java package pack1; class Student{ // Declaration of Instance variable. int roll=12; // here instance variable is default. // Declare the method. void name() // Here method has been defined with default access modifier. { System.out.println(" Hello Java"); } }
    // Save by College.java package pack2; import pack1.*; class College{ // Main method. public static void main(String[] args) { // Creating the object of the class Student from pack2. Student obj=new Student(); // Compile time error. because class Student has been defined with default access modifier and cannot be instantiated from outside the package. but if it is public then we can instantiate from outside the package. obj.name(); // Compile time error. because of the Default access modifier. } }
3. Protected(Inherited access modifier) 
Protected access specifiers can be applied to the instance variable, local variable, constructor, methods, inner class but not the outer class.
➲ Protected members are accessible inside the class and everywhere within classes in the same package and outside the package but through inheritance only.
➲ Protected members can be inherited to subclass.
➲ If we make constructor as protected then we can create the subclass of that class within the same package but not outside the package.

Let's take a simple example to understand the concept.
In this example, we have created the two packages pack1 and pack2. The Student class of pack1 package is public so it can be accessed from outside the package. but the name() method of this package is declared as protected. So it can be accessed from outside the class only through the inheritance.
Program 4:
    // Save by Student.java package pack1; public class Student{ // Declaration of Instance variable. int roll=12; // here instance variable is default. protected void name() // Here method has been defined with protected access modifer. { System.out.println("My roll no. is 12"); } }
    // Save by College.java package pack2; import pack1.*; class College extends Student { public static void main(String args[]) { // Creating the object of class Student from pack2. Student obj=new Student(); // Calling the method using reference variable obj. obj.name(); } }
    Output: My roll no. is 12.
4. Public(Universal access modifiers)
➲ Public access specifiers can apply to the instance variable, constructor, inner class, outer class, method but not a local variable.
➲ Public members can be used anywhere.
➲ Public members can be inherited to any subclass.
Program source code 4:
    // Save by Student.java package pack1; public class Student{ int roll=12; // here instance variable is default. public void name() // Here method has been defined with protected access modifer. { System.out.println(" My roll no. is 12"); } }
    // Save by College.java package pack2; import pack1.*; class College extends Student { public static void main(String args[]) { // Creating the object of class Student from pack2. Student obj=new Student(); obj.name(); } }
    Output: My roll no. is 12.
Private Protected Access
A variable or field can be declared with two keywords as private and protected together like this:
   private protected int age;
It provides the visibility level in between the "protected access" and "private access". This specifier makes the variable visible in all the subclasses regardless of what package they are in but the field cannot be accessed by other classes in the same package.

Visibility of Access Specifier in Java 

A table summarizes the visibility of various access modifiers.
Access location Public Protected Default Private protected Private
Same class Yes Yes Yes Yes Yes
Subclass in same package Yes Yes Yes Yes No
Other classes in same package Yes Yes Yes No No
Subclasses in other package Yes Yes No Yes No
Non-subclasses in other packages Yes No No No No

Key of access modifier(Always remember)

    Private  >  Default  >  Protected  >  Public
   More restrictive ----------------> Less restrictive.
                                      Decreasing
Final Words: 
We hope that this article has covered all the important points related to the Access Modifiers in Java. You always keep in mind the key of access modifier. It is very helpful to remember the concept. Non-access specifiers will be explained in the further tutorial.

More on Access Modifiers:
1. Access Modifiers Interview Questions 

Next ➝ Access Modifiers Interview Questions                                                              Scientech Easy loves you