Categories: Java

Non-access modifiers

Non-access modifiers provide the JVM with information about a class, method, or variable’s characteristics. In Java, there are seven different types of Non-Access modifiers:

  1. static
  2. final
  3. abstract
  4. synchronized
  5. volatile
  6. transient
  7. native
Static:
  • The static keyword indicates that the entity to which it is applied is accessible from any instance of the class.
  • The static keyword is used to create variables and methods that will exist regardless of whether the class is used.
  • Regardless of the number of instances of the class, there is only one copy of the static variable.
  • They can be called without having to create a class object.

Example:

import java.io.*;
  
// static variable
class Static_demo {
    static String s = "Coderzy"; 
}
class Demo {
    public static void main(String[] args)
    {
        // No object required
        System.out.println(Static_demo.s); 
    }
}

Output:

Coderzy
Final:
  • The final keyword indicates that the specific class or method cannot be extended or overridden.
  • A reference variable that has been declared final can never be reassigned to another object.
  • Any subclasses cannot override a final method.
  • The data within the object, however, can be changed. As a result, the object’s state can be changed but not its reference.

Example:

import java.io.*;
  
class Final_demo{
    final void myMethod(){
        System.out.println("Coderzy");
    }
}
class override_final_demo extends Final_demo{
    // trying to override the method available on final_gfg class
    void myMethod(){ 
        System.out.println("Overrides Coderzy");
    }
}
class Demo{
    public static void main(String[] args) {
        override_final_demo obj=new override_final_demo();
        obj.myMethod();
    }
}

Output:

javac /tmp/i3EnX2DS9r/Demo.java
/tmp/i3EnX2DS9r/Demo.java:10: error: myMethod() in override_final_demo cannot override myMethod() in Final_demo
void myMethod(){ 
^
  overridden method is final
1 error

Because we are attempting to override a method that is declared as final, the above code generates an error. We’re attempting to override myMethod() in the override_final_demo class, which is declared as final.

Abstract:
  • When the abstract keyword is used to declare a class as partially implemented, it means that it cannot be used to create an object directly.
  • Any subclass must either implement all the abstract class’s methods or be an abstract class in its own right.
    The class should be declared abstract if it contains abstract methods. Otherwise, a compilation error will occur.
  • Both abstract and regular methods can be found in an abstract class.

Example:

// abstract class
abstract class abstract_gfg{
  abstract void myMethod();
}

//extending abstract class
class MyClass extends abstract_gfg{
 
 // overriding abstract method otherwise
 // code will produce error
 void myMethod(){
  System.out.println("GeeksforGeeks");
 }
}
class GFG{
 public static void main(String[] args) {
  MyClass obj=new MyClass();
  obj.myMethod();
 }
}

Output:

Coderzy
Synchronized:
  • The synchronized keyword prevents a block of code from being executed simultaneously by multiple threads.
  • For some critical operations, it is very important.
  • Any of the four access level modifiers can be combined with the synchronized modifier.

Example:

import java.io.*;

class Counter{
 int count;
 void increment(){
  count++;
 }
}
class Demo{
 public static void main(String[] args) throws InterruptedException {
  Counter c=new Counter();
  
  // Thread 1
  Thread t1=new Thread(new Runnable() {
   @Override
   public void run() {
    for(int i=1;i<=10000;i++){
     c.increment();
    }
   }
  });
  
  // Thread 2
  Thread t2=new Thread(new Runnable() {
   @Override
   public void run() {
    for(int i=1;i<=10000;i++){
     c.increment();
    }
   }
  });

  t1.start();
  t2.start();
  t1.join();
  t2.join();

  System.out.println(c.count);
 }
}

Output:

20000

. Because both threads are accessing the count value, it’s possible that Thread1 fetches the value and, before Thread2 can increment it, Thread2 reads the value and increments it. As a result, the outcome may be less than 20000. The synchronized keyword is used to solve this problem. If the synchronized keyword is used when declaring the increment() method, a thread must wait for another thread to finish the method’s operation before continuing to work on it.

Volatile:
  • Thread safety is achieved by using the volatile keyword.
  • If a variable is declared volatile, it can be changed by multiple threads at the same time without causing any problems.
  • The volatile keyword applies only to variables.
  • A volatile keyword lowers the possibility of memory inconsistency.

Example:


import java.io.*;
import java.util.*;
 class MyRunnable implements Runnable {
   private volatile boolean active;

   public void run() {
      active = true;int k=0;
      while (active) {   // line 1
         // some code here
         k++;
         System.out.println(k);
      }
   }

   public void stop() {
      active = false;   // line 2
   }
}
class Demo{
    public static void main(String[] args) {
        MyRunnable obj = new MyRunnable();
        obj.run();
        Scanner input = new Scanner(System.in);
        input.nextLine();
        obj.stop();
    }
}

Output:

java -cp /tmp/8E2dLPWDK6 Demo
1
2
3
4
5
6
7
8
9
10
.
.
.
828
829
830
831

Typically, run() is called from one thread (the one from which the Runnable was created), and stop() is called from another thread. If the cached value of active is used in line 1, the loop may not end when active is set to false in line 2. That’s when volatile comes in handy.

Transient:
  • When an instance variable is marked transient, the JVM knows to skip it when serializing the object that contains it.
  • This modifier appears before the variable’s class or data type in the statement that creates the variable.
Native:
  • A method can be given the native keyword to indicate that it is written in a language other than Java.
  • This Java application allows you to call code written in C, C++, or assembler.

Note: also read about the Constructor in Java

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago