Access Modifiers in Java – A Step towards Improving your Skills!

A fundamental part of object-oriented programming is restricting access to the members of a class because it helps to prevent the misuse of an object. In Java, we are able to accomplish encapsulation through the appropriate use of access modifiers. We can avoid invalid assignment of values to the data by allowing only a well-defined set of methods to access the private data – for example by performing a range check inside the method.

By this tutorial, get brief learning about access modifiers in Java. Also, you will learn about the 4 types of access modifiers that is, public, private, default and protected. But before that, you first need to understand the concept of Java Class.

Access Modifiers in Java

Accessing a member of a class depends a lot on the access levels or access modifiers. Access modifiers provide access to members of a class within a Java program. A Java access modifier specifies which classes can access a given class and its fields, methods, and constructors. We can use access modifiers for a class, its constructors, fields, and methods. Access Modifier is also called a visibility modifier.

In Java, there can be 4 access modifiers that can be used with classes, methods, fields, and constructors:

  • public
  • default
  • private
  • protected

Access Modifiers in Java

Today, we will go through each of the access modifiers in Java in detail.

1. private access modifier

The private access modifier in Java denotes that a variable or a method is private to the class and we cannot access them outside the class. That is, we can access the variable or call a method only from inside the class. Not even subclasses of the same class or any other external class can access these private variables methods.

The private modifier is the most restrictive access level. It is accessible only within the class. This access modifier should be used to declare the members that should be only used by the class.

We cannot mark a class with a private access modifier in Java!!

Declaring a class with the private access modifier would mean that no other classes can access it, which means we can not really use the class at all. Using private with the main class or top-level class is useless because none of the members can have access to it. Therefore, Java does not allow private access modifier for the classes. The Java compiler gives an error when we try to declare our main class as private.

Syntax of declaring private members:

To declare a private member, we need to use the keyword private.

class Example {
  private datatype privatemember1;
  private privateMethod()
  {
     //code of privateMethod();
  }
}

Code Snippet to understand the private modifier:

class Alpha
{
private int iAmPrivate;  	//private data member
  private void privateMethod()	//private method
  {
    System.out.println("I am a private method");
  }
}

/* Objects of Alpha can modify the value of iAmPrivate variable and invoke privateMethod(). As shown below*/

public static void main(String args[])
  {
    Alpha object1 = new Alpha();
    /*Accessing private variables or private method outside their classes raises an error*/
    object1.iAmPrivate = 10;
    System.out.println("Value of private member is: " +object1.iAmPrivate);
    object1.privateMethod();
  }
}

Output:

Value of private member is: 10
I am a private method

But, when we try to access the members of the Alpha class with the objects of other classes, then we will get an error as the private members are accessible only within the Alpha class. For example, class Beta cannot access them as shown:

class Beta 	//declaring another class
{
  public static void main(String args[])
  {
           Beta object1 = new Beta();
           object1.iAmPrivate = 10;
           System.out.println("Value of private member is: " +object1.iAmPrivate);
           object1.privateMethod();
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problems:
The field Alpha.iAmPrivate is not visible
The field Alpha.iAmPrivate is not visible
The method privateMethod() from the type Alpha is not visibleat project1/OperatorsInJava.Beta.main(Beta.java:5)

2. default access modifier

If no access modifier is used, then the class members have default access – known as package or friendly access. Java assumes this access modifier when we do not explicitly set any access level of the class members. This assumes that all classes in the same package are friends. A package is a logical group of related classes.

The default access modifier means that the class, its default fields, constructors and methods are accessible only within the class itself and within all the classes in the same package. Therefore, the default access modifier is also sometimes known as the package access modifier.

The Subclasses (child classes) cannot access the default methods and member variables (fields) in the superclass unless this subclass is present in the same package as the superclass (parent class).

Syntax of declaring default members:

To declare a default member, we need not use any keyword:

class Example {
  datatype defaultmember1;
  defaultMethod()
  {
      //code of defaultMethod();
  }
}

Code Snippet to illustrate the default access modifier:

package com.TechVidvan.defaultDemo1;
class Alpha
{
  int iAmDefault; 	//default data member
  void defaultMethod() // 	method declared as default
  {
      System.out.println("I am a default method inside package DefaultDemo1");
  }
}

//Using the default members inside the different class but within the same package

package com.TechVidvan.defaultDemo1;	//same package is used
class Beta {			//Different class
  public static void main(String args[])
  {
    Alpha object1 = new Alpha();
    object1.iAmDefault = 20;
    System.out.println("Value of private member is: " +object1.iAmDefault);
    object1.defaultMethod();
  }
}

Output:

Value of default member is: 20
I am a default method inside package DefaultDemo1

Accessing the default members inside the different class from different package gives an error –

package com.TechVidvan.defaultDemo2;	//inside a different package
import defaultDemo1.*;
class Beta
{
  public static void main(String args[])
  {
             Beta object1 = new Beta();
             //Accessing the members from different package gives an error
             object1.iAmDefault = 10;
             System.out.println("Value of default member is: " +object1.iAmDefault);
             object1.defaultMethod();
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problems:
iAmDefault cannot be resolved or is not a field
iAmDefault cannot be resolved or is not a field
The method defaultMethod() is undefined for the type Betaat project1/DefaultDemo2.Beta.main(Beta.java:9)

3. protected access modifier

The protected access modifier in Java denotes that the variable or a method is accessible to its subclasses but private to all other classes outside the current package. It allows access to the class itself, subclasses and all classes in the same package to access the members. It is also accessible to the subclasses which are not located in the same package as of superclass.

So, we can say that the scope of the protected access modifier is within a package and, also outside the package, but with the help of inheritance.

Syntax of declaring default members:

To declare a member as protected, we need to use the keyword protected.

class Example {
  protected datatype protectedmember1;
  protected protectedMethod()
  {
       //code of protectedMethod();
  }
}

Code Snippet to illustrate the protected access modifier:

package com.TechVidvan.protectedSpecifierDemo1;
class Alpha
{
  protected int iAmProtected;  		//protected data member
  protected void protectedMethod()  	//protected method
  {
    System.out.println("I am a protected method.");
  }
}

//Accessing the protected members inside the same package but different class.

package com.TechVidvan.protectedSpecifierDemo1;
class Beta
{
  public static void main(String args[])
  {
     Alpha object1 = new Alpha();
     object1.iAmProtected = 30;
     System.out.println("Value of protected member is: " +object1.iAmProtected);
     object1.protectedtMethod();
  }
}

Output:

Value of protected member is: 30
I am a protected method.

Now let us try to access the protected members from the subclass Delta within the same package, which inherits the class Alpha (parent class) –

package com.TechVidvan.protectedSpecifierDemo1;
class Delta extends Alpha
{  	//it means class Delta inherits members of class Alpha
   	public static void main(String args[])
   	{
    Delta d = new Delta();
    d.iAmProtected = 40;
    System.out.println("Value of protected member is: " +d.iAmProtected);
    d.protectedtMethod();
   	}
}

Output:

Value of protected member is: 40
I am a protected method.

4.  public access modifier

The public access modifier in Java denotes that a class member, method, constructors or any field are accessible directly from all other classes and packages, irrespective of the location of the code. The public members can be accessed from different classes and different packages.

That is, any class, in any package, has access to the public members of a class. We can globally access member variables or methods, without any restriction.

Using this access modifier is the easiest way to provide access to class members. However, we should be careful while using this keyword with class variables, otherwise, anybody can manipulate the values.

Syntax of declaring public members:

To declare a public member, we need to use the keyword public.

class Example {
  public datatype publicmember1;
  public publicMethod()
  {
      //code of publicMethod();
  }
}

Code Snippet to understand the public modifier:

package com.TechVidvan.publicSpecifierDemo1;
class Alpha
{
  public int iAmPublic;  		//public data member
  public void publicMethod()  	//public method
  {
    System.out.println("I am a public method");
  }
}

//Accessing public members from inside a different class from a different package

package com.TechVidvan.publicSpecifierDemo2;
import publicSpecifierDemo1.*;
class Beta
{
  public static void main(String args[])
{
    Beta object1 = new Beta();
    //Accessing the members from different package
    object1.iAmPublic = 50;
    System.out.println("Value of public member is: " +object1.iAmPublic);
    object1.publicMethod();
  }
}

Output:

Value of public member is: 50
I am a public method.

The following table shows the accessibility of all the different access modifiers:

accessibility of access modifier in Java

Summary

Access Modifiers in Java provide the means by which we can control the access of the class members. By this article, we could clearly understand that with the help of Access Modifiers in Java, we can prevent the misuse of the members and ensure their security by restricting their usage. We can manually set the visibility modes and scope of the members of a class.

Hope you liked our article. Don’t forget to share your feedback through the comment section below.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.