Access Specifiers in Java Example

Modifiers in Java


A modifier is a keyword that we add to those definitions to change their meaning. In other words, It limits the visibility of the classes, fields, constructors or methods in the Java program. 

The functionality of the members of a class or a class itself can be protected from other parts of the program by the presence or absence of modifiers. Java language provides a total 12 modifiers. They are public, private, protected, default, final, synchronized, abstract, native, strictfp, transient, and volatile.

Twelve modifiers can be divided into two categories: access modifiers and non-access modifiers. Access modifiers are also called access specifiers in java.Modifiers in Java

In this tutorial, we will learn the following topics in detail under access modifiers.

Access Specifiers in Java


Access modifiers/specifiers in java define the boundary for accessing the members of a class and a class itself. In other words, access specifiers are those modifiers that are used to restrict the visibility/accessibility of classes, fields, methods, or constructors. 


In short, the accessibility/visibility of data depends on the access specifiers. The access specifiers are also known as visibility modifiers. Java provides four explicit access modifiers in object-oriented languages. They are private, default, protected, and public.

Java supports four types of access modifiers.Access specifiers in java

Private Access Modifier in Java


➲ Private access specifier in java 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) of a class cannot be accessed from outside the class. They are accessible only within the class.
 
➲ Private members of a superclass cannot be inherited to the subclass. Therefore, they are 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, the members of the class can be private.
➲ If we declare a method as private, it behaves as a method declared as final. We cannot call the private method from outside the class.

Let us create a program where we will create two classes Class A and Class B. In class A, we will declare field and method as private. When we will access this private field and private method from outside the class B, then they will give a compile-time error.
Program source code 1:
package modifiersProgram; 
 class A // Here, Class is default. 
  { 
// Declaration of Instance Variable. 
    private int data = 30; // Here instance variable is private. 

// Declaration of instance method. 
     private void msg() // Here method is also private. 
     { 
        System.out.println("Hello Java, this is my first java program"); 
     } 
}

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 an object of class A and call members of class A using reference variable 'a'. 
     A a = new A(); // a is a reference variable of class A and pointing to the objects of class A. 
     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 an object of the class from outside the class. In other words, we cannot create the subclass of that class.

Let’s take an example program where we will declare a constructor of class as private and try to create an object of that class. But, we will get a compile-time error.
Program source code 2:
package modifiersProgram; 
 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 from class B. As you will call 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. The outer class is also known as top-level class. The only five modifiers are applicable to a top-level class. They are public, default, final, abstract, and strictfp.

By mistake, if you will try to use any other modifiers with top-level class, you will get a compile-time error: “Modifier private not allowed here“.

Default Access Modifier in Java


➲ When access specifier is not specified to members of a class or a class itself, it is called default access specifier.
➲ The default can apply to the instance variable, local variable, constructor, methods, inner class, or outer class.

➲ Default members of a class are visible inside of the class and everywhere within classes in the same package or folder only. Therefore, they can be accessed from outside the classes in the same package but can not be accessed outside the package.

➲ Default members can be inherited to the subclass within the same package only. It cannot be inherited from outside the package.

Let’s understand the default access modifier or specifier better with an example program.

In this example program, we have created two packages pack1 and  pack2. We are accessing class A from outside its package since class A is a default, not public. Therefore, it cannot be accessed from outside the package.

Program source code 3:

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"); 
    } 
}
package pack2; 
import pack1.*; 
class College 
{ 
// Main method. 
   public static void main(String[] args) 
   { 
// Creating the object of the class Student from package 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 declared as public then we can instantiate from outside the package. 

     obj.name(); // Compile time error because of the default access modifier.
    }
 }

Protected Access Modifier in Java


➲ 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 the 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 an example program to understand the concept of default access specifier.

In this example, we have created 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 source code 4:

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"); 
   } 
}
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.

Public Access Modifier in Java


➲ Public access specifier can apply to the instance variable, constructor, inner class, outer class, method but not a local variable.
➲ Public members of a class can be used anywhere.
➲ Public members of a class can be inherited to any subclass.

Let us take an example program related to public access specifier.

Program source code 4:
package pack1; 
public class Student 
{ 
  int roll = 12; // Here, instance variable is default. 
  public void name() // Here, method has been defined with protected access modifier. 
  { 
    System.out.println(" My roll no. is 12"); 
  } 
}
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 in Java


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 below table summarizes the visibility of various access modifiers in java.

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 modifiers

   Private  >  Default  >  Protected  >  Public
   More restrictive —————-> Less restrictive.

                              Decreasing

Applicable modifiers with Classes, Methods, Variables, Interfaces, etc.

Outer Class (Top-level Class)

1. The only five modifiers are applicable to the outer class. They are public, default, final, abstract, and strictfp. 
2. Final and abstract both cannot be applied simultaneously with a class. It is an illegal combination. 
3. If a class is declared as public, private or protected cannot be applied simultaneously with public class. It is also an illegal combination.

Inner Class

1. The applicable modifiers for the inner class are public, private, protected, default, final, abstract, static, and strictfp.
2. The non-applicable modifiers for inner class are synchronized, native, transient, and volatile.
3. The modifiers which are not applicable for inner classes but not applicable for outer classes are private, protected, and static.

Methods

1. The only two modifiers out of 12 that are not applicable for methods are transient and volatile.
2. If a method is declared as public, we cannot declare simultaneously private or protected with a public method.
3. If a method is defined as abstract, we cannot apply final, static, synchronized, native, private, or strictfp.

Variables

1. The modifiers applicable for variables are public, protected, private, default, final, static, transient, and volatile.
2. The non-access modifiers such as abstract, synchronized, native, and strictfp are not applicable for variables.
3. The only applicable modifier with local variable is final. If a variable is declared as final, we cannot declare as volatile.

Constructors

1. For a constructor, only access modifiers are applicable. The access modifiers like public, protected, default, and private that can be applied with constructors. 
2. Non-access modifiers cannot be applied with constructors. By mistake, if you apply any other modifiers with constructor except these four access modifiers, you will get a compile-time error.

Blocks

Static and synchronized modifiers are only applicable for blocks.

Outer Interface

1. Public, default, abstract, and strictfp are such modifiers that are applicable for outer interface. Except for these modifiers, we cannot apply other modifiers with outer or top-level interface. 
2. The non-access modifier that is applicable for classes but not applicable for an interface, is final.

Inner Interface

1. For inner interface, we can apply modifiers like private, default, protected, public, abstract, static, and strictfp. 
2. The non-access modifiers such as final, synchronized, native, transient, and volatile are not applicable for inner interface.

Outer Enum

1. The only three modifiers like public, default, and strictfp are applicable for outer enum.
2. The modifiers which are applicable for classes but not applicable for enum are final and abstract. 

Inner Enum

1. For enum, we can apply all four access modifiers and two non-access modifiers like static, and strictfp.

 

Final words
Hope that this tutorial has covered almost all important points related to access modifiers/specifiers in java with example programs. I hope that you will have understood access specifiers and their application. In the next tutorial, we will discuss non-access modifiers in java.
Thanks for reading!!!
Next ⇒ Non-access modifiers in Java⇐ PrevNext ⇒

Leave a Comment