{{announcement.body}}
{{announcement.title}}

Access and Non-Access Modifiers in Java

DZone 's Guide to

Access and Non-Access Modifiers in Java

Learn more about the different types of modifiers in Java.

· Java Zone ·
Free Resource

In Java, a modifier has a reserved keyword that is included in the definition of class, method, and variables. A modifier adds some meanings to these definitions. Modifiers are also called specifiers.

These modifiers are classified into two categories. Some of the modifiers are called access modifiers and some are called non-access modifiers.

Access modifiers are reserved keywords that provide a different level of access to classes, methods, fields, etc. Reserved keywords for access modifiers are public, protected, and private.


Access Modifiers in Java

Access modifiers are further classified into the following categories:

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

You may be interested in studying this Java Tutorial.

Default Access Modifier

Default Access Modifier does not require to use any reserved keyword. Any method or variable with default access modifier can be accessed from any class in a package. It behaves almost similar as public access modifier but there is a difference between them. In an interface, variables are public static final and methods are public by default.

class Car{        //initialization of class

 Car object1;     // object declaration

 void moveForward(){      //void method
    //method body
 }

}  //end of class


Public Access Modifier

In a Public Access Modifier, the keyword public is used before variable, method, class, or constructor. A public method or variable can be accessed in any class, even the class that belongs to a different package. If a class belongs to a different package, we can import it using inheritance.

public class Car{        //initialization of class

  public Car object1;     // object declaration

  public void moveForward(){      //void method
   //method body
  }

}                 //end of class


Protected Access Modifier

In a Protected Access Modifier, the keyword protected is used before a variable, method, and constructor. No class can have protected access modifier. Any variable, method, or constructor with a protected access modifier is only accessible within child classes or subclasses of superclasses in which it is declared.

public class Car{        //initialization of class

 protected Car object1;     // object declaration


 protected void moveForward(){      //void method
    //method body
  }

  }                 //end of class


You may be interested in studying this article on Cyber Security TRIADS.

Private Access Modifier

In a Private Access Modifier, the keyword private is used before variable, method, and constructor. A class and interface cannot be private. A class can have private access modifier only if it is an inner class, i.e. a class is a member of another class. Private provides the most restricted level of access. To access any variable or field outside of the class in which it is declared, setter and getter methods are used. Getter  methods are used to access the variable outside class, and setter methods are used to set values for these private fields in a class where these are declared.

public class Car{        //initialization of class

private Car object1;     // object declaration


  private void moveForward(){      //void method
   //method body
    }


  private class Horn{   //inner class with private access modifier

  }                      
  }                 //end of class


Non-Access Modifiers

Non-Access Modifiers are further classified as:

  1. Static Modifier
  2. Final Modifier
  3. Abstract Modifier
  4. Synchronized Modifier
  5. Transient Modifier
  6. Volatile Modifier

Static Modifier

Static Modifier is used for creating a static variable and static method. The reserved keyword for a static modifier is static, which is used before the data type of the variable or method. A static method or variable exists independently of any class object. It means a static variable or static method can be called using the class name without creating an instance or object of this class.

For example, in theCar.java class below, at line 3, a static variable msg is declared. At line 5, a void method is declared, which will print the value of static variable msg on screen. Syntax is ClassName.Variable.

Car.java

public class Car{

  public static String msg;       //String type static variable is declared

  public static void create(){

     System.out.print(msg);   //Variable msg is passed as argument to print.
  }

}


In the Main.java class, at line 6, without creating any object of class Car, we initialized the static variable msg in the Car class and invoked create() method in class Main defined in the Car class. Syntax is ClassName.Method.

Main.java

public class Main{        //initialization of class

  public static void main(String[] args){

      //value is stored in static variable
       Car.msg = "A new car has been created"; 

      // static method in class Car is invoked
      Car.create();                           

    }                     
 }                 //end of class



static-access-modifierOUTPUT 2 – MAIN.JAVA

Final Modifier

In Java, variable, method, and class can have a final non-access modifier. The reserved keyword for a final non-access modifier is final. This keyword is used to make any class, method, or variable final.

Once a final variable is initialized, you cannot change its value again. A final variable that is uninitialized is called a blankfinal variable that can be initialized only in the constructor of a class. To make a class variable, sometimes, we use the static keyword with final. If a static final variable is not initialized, we can initialize it in a static block.

Code Example for Final Variable With Error:

 public class Main{        //initialization of class

   //declare a final variable of int data type
   public final int number = 1; 

   //non-static method to print number value
    public void print(){

         System.out.print(number); //print number

           number = 2; //change value of number

         System.out.print(number); //print new value

   }

   // main method
    public static void main(String[] args){

      //object of class Main to access non-static methods
       Main p = new Main(); 
       //print method invoked
        p.print();

     }       
   }                 //end of class


final-access-modifierCOMPILE TIME ERROR DUE TO REASSIGNING VALUE TO FINAL VARIABLE


If we remove code at line 11, the modified code would be executed without any error.

Code Example for Final Variable:

public class Main{        //initialization of class

   //declare a final variable of int data type
   public final int number = 1; 

    //non-static method to print number value
    public void print(){

         System.out.print("Output is "+number); //print number

   }

   // main method
   public static void main(String[] args){

      //object of class Main to access non-static methods
       Main p = new Main(); 
      //print method invoked
        p.print();

     }       
  }                 //end of class

final variable

Code Example for Static Final Variable:

public class Main{        //initialization of class

    //declare a static final variable of int data type
    public static final int number = 1; 

    // main method
    public static void main(String[] args){

      System.out.print("Output is "+number); //print number

    }       
  }                 //end of class


A method that we cannot override is called finalmethod. It can be inherited in any other class.

Code Example for Final Method:

Car.java

public class Car{

  //final method
  public final void create(){

     System.out.print("I'm final method to create a car."); 
  }

}


Main.java

 //initialization of class
 public class Main extends Car{        

     //non-static method to access non-static methods in Car.java        
     public void makeCar(){
        create();       //method invoked
     }           
    // main method
   public static void main(String[] args){

        Main m = new Main(); //object of Main class
        m.makeCar();        //call to makeCar method

    }       //end of main method
  }                 //end of class

final-method-example-in-java

A class that we cannot extend is called finalclass. It means a final class cannot be inherited by any other class.

Code Example for Final Class:

Car.java

public final class Car{

  //void method
  public void print(){
     //method body
  }

}


Main.java

   //initialization of class
   public class Main extends Car{        


     public static void main(String[] args){


      }       //end of main method
   }                 //end of class

final-class-example

Abstract Modifier

A class or method can be declared as abstract. Reserved keyword abstract is used for the abstract modifier.

An abstract class or method cannot be final because an abstract class is made with the purpose of extending it in other classes and an abstract method is made for the sole purpose of overriding the method body. To make a class abstract, at least one abstract method should be defined in a class. If we have to declare abstract methods in a class, a class must be an abstract class.

An abstract method is just a declaration; it does not contain an implementation or method body. You will have to define its implementation by overriding this method in a class, which has extended the abstract class. When a class extends an abstract class, all the abstract methods defined in the abstract class must be overridden in a subclass.

Car.java

public abstract class Car{

  public abstract void create();
  public void print(){

      System.out.print("I'm not abstract method.");

  }

}


Main.java

   //initialization of class
   public class Main extends Car{        

       // overriding method defined in Car class   
       //as create is only abstract method in Car class
       //overriding it is compulsory
       //otherwise error will occur
       @Override
       public void create(){

          System.out.println("I'm overridden method.");

      }

      // main method
      public static void main(String[] args){

          Main m = new Main(); //object of Main class
          m.create();          //invoking overridden method
          m.print();

      }       //end of main method
   }                 //end of class

abstract-class-and-abstract-method

Volatile Modifier

This modifier is applied only to private or object type instance field or variable. Reserved keyword for this modifier is volatile.

It indicates to the JVM to merge a thread’s own copy of field with the master copy of field available in memory. When we access a volatile variable, it synchronizes all the available cached copies of variables in memory.

  public class Salary implements Runnable {
    private volatile int salary;

    public void run() {
       salary = 5000; //assigning value to salary
     do{

        //loop body

    }
      while (salary <= 5000); // while loop definition
   }

   public void stop() {
      salary = 5001;   // new value assignment to salary
   }
}


Transient Modifier

When we use a transient modifier in an instance variable declaration, the JVM will skip this variable or field while serializing the object containing that variable. Reserved keyword is transient.

 public abstract class Car{

   //instance variable with transient modifier
   public transient int number = 22114; 

}


Synchronized Modifier

A modifier that is used to restrict a method to be used by any other thread when it is under use of one thread. Reserved keyword for this modifier is  synchronized.

The synchronized modifier can be used with any access modifier.

 public abstract class Car{

   public synchronized make(){
       //method body
   }   
}


That's all for this post on access and non-access modifiers in Java. 

Happy modifying!

Topics:
modifier ,java ,non-access ,access ,static ,final ,abstract ,volatile ,transient ,synchronized

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}