Modifiers in Java

Java offers special keywords known as modifiers. These modifiers are of two types: Access modifier and Non-Access specific modifier. In this tutorial, we will learn about these keywords.

1. Java Access Modifiers

In Java, there are certain keywords that we can write in front of variables, methods and classes to change their access levels. These are called access modifiers. Access modifiers are used to restrict the accessibility of the variable, method or class. There are four main access modifiers in Java: public, protected, default and private.

Syntax of class, method and variable declaration with access modifiers:

[modifier] class ClassName{

    //variable declaration
    [modifier] dataType variableName;

    //method declarations
    [modifer] returnType methodName(){//code}
}

Now, let us look into access modifiers in detail:

a. Public

A variable, method or class declared as public is accessible to all. Any class can access it within the same package or another package.

class Tutorial{  

public void printMessage(){
  System.out.println("FirstCode is sharing tutorials!");
}  
}  
public class FirstCode{  
public static void main(String args[]){  
   Tutorial t = new Tutorial();
   t.printMessage();
   }  
} 

Output:

FirstCode is sharing tutorials!

In the above example, as printMessage() is a public method, we could access it from another class. A block of code declared as public can be accessed from the same class, another class or even another package, i.e., it is publicly accessible to everyone.

b. Protected

Any block of code that has the protected access modifier can be accessed by any class within the same package and by subclasses in another package through inheritance. That is, anyone in the same package can access protected data, and only through children classes of the protected class in other packages.

class FirstCode {

    protected int tutorialNumber = 5;
    protected void message(){ 

System.out.println("This is tutorial number: "); 

}
}

class Tutorial extends FirstCode{

    public static void main(String[] args)
    {
        Tutorial t1 = new Tutorial();
        t1.message();
        System.out.println(t1.tutorialNumber);
    
    }
}

Output:

This is tutorial number:
5

In the above example, we accessed the protected variables and methods of the parent class FirstCode using an object of the child class Tutorial.

c. Default

Any class can access a code block specified as default within the same package. A class with no access modifier explicitly mentioned has default access.

package FirstCode;

class FirstCode{
    void printMessage()
    {
        System.out.println("Hello FirstCode”);
    }
}

The above code had default access, as no other modifier has been mentioned. A class within the same package can access the methods in class FirstCode.


package FirstCode;

class FirstCode{
    void printMessage()
    {
        System.out.println("Hello FirstCode”);
    }
}

class First extends FirstCode(){
    public static void main(String args[]){
        First f = new First();
        f.printMessage();
}
}

Output:

Hello FirstCode

However, if we try to access the method from another class, even if it’s a subclass of FirstCode, it cannot access the default methods.

For Example

package firstcode;

class FirstCode{
    void printMessage()
    {
        System.out.println("Hello FirstCode");
    }
}
package firstcode2;
import firstcode.*;

class FirstCode2 extends FirstCode
{
    public static void main(String args[])
    {
        FirstCode2 f2 = new FirstCode2();
        f2.printMessage(); //Compile Time Error
    }
}

Output:

error: “FirstCode is not public in firstcode; cannot be accessed from outside package.”

d. Private

Code which is declared private is accessible only to members within that class. That is, private code cannot be accessed by any other class, whether within the same package or not.

class Tutorial{  
    private int tutorialNumber = 10;  
    
    private void printMessage(){
    System.out.println("This is tutorial " + tutorialNumber);
    }  
}  
      
public class FirstCode{  
    public static void main(String args[]){  
        Tutorial t = new Tutorial();
        t.printMessage(); //Compile-time error
    }  
} 

Output:

error: printMessage() has private access in Tutorial

Here is a snapshot of the access levels of the various modifiers:

java access modifiers

Java access modifiers and their access levels

2. Java Non-access modifiers

These are special keywords that provide certain functionalities rather than controlling access levels. Non-access modifiers in Java include:

a. Abstract

They are used to declare abstract classes having methods with no method body. An abstract class has to be inherited and instantiated by a child class. We will learn more about abstract classes here.

b. Final

It is used to prevent a class from being inherited, a variable from being overwritten and a method from being overridden. We will learn more about final classes in later tutorials.

c. Static

Static variables and methods belong to a class rather than an object. You can learn more about static classes in a separate tutorial.

d. Synchronized

Synchronised keywords work with blocks and methods in Java. It facilitates the locking of shared data, ensuring that such data is available for access to only one single thread at a particular instance of time. This prevents race condition from occurring between threads..

e. Native

Java native keyword applies only to methods and is used to signify a method implemented using Java Native Interface (JNI).

f. Transient

In Java, we can use transient keywords with them when we want to prevent the serialisation of certain attributes and methods.

g. Volatile

The volatile keyword is used with variables we want to modify by several threads. In Java, the volatile keyword reads the variable’s value from the main memory and does not cache its value.

Summary

In this tutorial, we learned about special keywords in Java called modifiers. These modifiers can either help in controlling access levels of a block of code (access modifiers) or impart special properties to a block of code (non-access modifiers). Access modifiers are of four types: public, protected, private and default. Meanwhile, non-access modifiers are several such as abstract, final, static, synchronised, native, transient, and volatile.

Leave a Reply

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