Home> Java> javaTutorial> body text

Non Access Modifiers in Java

王林
Release: 2024-08-30 15:59:18
Original
402 people have browsed it

Non Access Modifiers are the keywords introduced in Java 7 to notify JVM about a class’s behaviour, methods or variables, etc. That helps introduce additional functionalities, such as the final keyword used to indicate that the variable cannot be initialized twice. There are a total of 7 non-access modifiers introduced.

  1. Static
  2. Final
  3. Abstract
  4. Synchronized
  5. transient
  6. strictfp
  7. native

Types of Non-Access Modifiers in Java

Below are the types of Non-Access Modifiers in Java:

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

1. Final Non Access Modifiers

This modifier can be applied with:

  1. Class
  2. Method
  3. Instance Variable
  4. Local Variable
  5. Method arguments

Non Access Modifiers in Java

  • Final Class: Final Keyword is used with a class when we want to restrict its inheritance by any other class. For example, If we have a final class Honda, then any attempt to extend this class can lead to a compile-time error.

Code:

final class Honda{ public void myFun1(){ System.out.println("Honda Class"); } } class Bike extends Honda{ public void myFun1(){ System.out.println("Bike Class"); } }
Copy after login

Output:

Non Access Modifiers in Java

  • Final Method:Final Keyword is used to indicate Java Runtime Environment that this method is not meant to be overridden in any of its subclasses.

Code:

class Honda{ public final void myFun1(){ System.out.println("Honda Class"); } } class Bike extends Honda{ public void myFun1(){ System.out.println("Bike Class"); } }
Copy after login

Output:

Non Access Modifiers in Java

  • Final Variable: The final keyword is used with a variable to restrict any modification to the variable’s value, thus indicating JVM to treat it as a constant. This means final variables can be initialized only once.

2. Abstract Non-Access Modifier

Non Access Modifiers in Java

  • Abstract Class: A class is declared as abstract to indicate that this class can not be instantiated, which means no objects can be formed for this class but can be inherited. Still, this class has a constructor that will be called inside the constructor of its subclass. It can contain abstract as well as final methods, where abstract methods will be overridden in the subclass.

Code:

public abstract class MyActivity{ public MyActivity(){ } public final String myFun1(){ } }
Copy after login
  • Abstract Method: Abstract methods are methods without any definition. It contains only the signature of the method and is meant to indicate that these need to be overridden in the subclass.

Example:public abstract void fun1();

Code:

abstract class Electronics { abstract void display(); abstract void display(String msg); } class Computers extends Electronics { @Override void display() { System.out.println("Abstract method is called"); } @Override void display(String txt) { System.out.println(txt); } } public class AbstractDemo { public static void main(String[] args) { Computers obj=new Computers(); obj.display(); obj.display("Method with arguments"); } }
Copy after login

Output:

Non Access Modifiers in Java

3. Synchronized Non-Access Modifier

Non Access Modifiers in Java

This keyword helps prevent the access of one method by multiple threads simultaneously, thus synchronizing the flow of a program and bringing out the desired results using the multithreading feature.

Code:

class Person1 { public synchronized void sendFun(String txt) { System.out.println("Sending message\t" + txt ); try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Thread interrupted."); } System.out.println("\n" + txt + "Sent"); } } class DemoThread extends Thread { private String txt; Person1 person; DemoThread(String m, Person1 obj) { txt = m; person = obj; } public void run() { synchronized(person) { person.sendFun(txt); } } } public class HelloWorld { public static void main(String args[]) { Person1 snd = new Person1(); DemoThread S1 = new DemoThread( " Hi " , snd ); DemoThread S2 = new DemoThread( " Bye " , snd ); S1.start(); S2.start(); // wait for threads to end try { S1.join(); S2.join(); } catch(Exception e) { System.out.println("Interrupted"); } } }
Copy after login

Output:

Non Access Modifiers in Java

4. Static Non-Access Modifier

Non Access Modifiers in Java

This variable is used for memory management and the first thing being referenced while loading a class. These members are treated on a class level; thus, they cannot be called using an object; instead, the name of the class is used to refer to them.

  • Static Variable:If a variable is declared as static, then only a single copy of the variable is created and shared among all the objects. Thus any change made to the variable by one object will be reflected in other others. Therefore, the variables that hold value on the class level is declared as static.
  • Static Class: Static keyword can only be used with nested classes.
  • Static Methods: Since Static Methods are referenced by class name thus can only access static member variables and other static methods. Also, these methods cannot be referred to using this or super pointer. The main method is the most common example of a static method that always get loaded while its class is being loaded.
  • Static Block:This is said to be a block being used to perform certain operations while class is being loaded. Since it is static thus can use only static members of the class.

Code:

public class Demo { // static variable static int x = 10; static int y; //static class public static class DemoInnerClass{ static int z=10; } // static block static { System.out.println("Static block initialized."); y = x + 4; } //static method public static void main(String[] args) { System.out.println("from main"); System.out.println("Value of x : "+x); System.out.println("Value of y : "+y); System.out.println("Value of z : "+DemoInnerClass.z); } }
Copy after login

Output:

Non Access Modifiers in Java

5. Native Non Access Modifier

Non Access Modifiers in Java

The native keyword is used only with the methods to indicate that the particular method is written in platform -dependent. These are used to improve the system’s performance, and the existing legacy code can be easily reused.

Note:Static, as well as abstract methods, cannot be declared as native.

Example:Consider a function myfun1 in class NativeDemo that is written in C++. To use this code, we will create a link library mylib1 and load it using the class’s static block.

public class DateTimeUtils { public native String getSystemTime(); static { System.loadLibrary("nativedatetimeutils"); } }
Copy after login

6. Strictfp Non-Access Modifier

Non Access Modifiers in Java

  • Strictfp Class / Method:This keyword is used to ensure that results from an operation on floating-point numbers brings out the same results on every platform. This keyword can not be used with abstract methods, variables or constructors as these need not contain operations.

Code:

public class HelloWorld { public strictfp double calSum() { double n1 = 10e+07; double n2 = 9e+08; return (n1+n2); } public static strictfp void main(String[] args) { HelloWorld t = new HelloWorld (); System.out.println("Result is -" + t.calSum()); } }
Copy after login

Output:

Non Access Modifiers in Java

7. Transient Non-Access Modifier

While transferring the data from one end to another over a network, it must be serialised for successful receiving of data, which means convert to byte stream before sending and converting it back at receiving end. To tell JVM about the members who need not undergo serialization instead of being lost during transfer, a transient modifier comes into the picture.

Syntax:

private transient member1;
Copy after login

Code:

import java.io.*; class Demo implements Serializable { int x = 10; transient int y = 30; transient static int z = 40; transient final int d = 50; public static void main(String[] args) throws Exception { Demo input = new Demo(); FileOutputStream tos = new FileOutputStream("abc.txt"); ObjectOutputStream tin = new ObjectOutputStream(tos); tin.writeObject(input); FileInputStream fis = new FileInputStream("abc.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Demo output = (Demo)ois.readObject(); System.out.println("x = " + output.x); System.out.println("y = " + output.y); System.out.println("z = " + output.z); System.out.println("d = " + output.d); } }
Copy after login

Output:

Non Access Modifiers in Java

Conclusion

Non-access modifiers are the type of modifiers that tell JVM about the behavior of classes, methods, or variables defined and prepared accordingly. It also helps in synchronizing the flow as well as displaying similar results from operations being performed irrespective of the platform used for execution.

Recommended Article

This is a guide to Non Access Modifiers in Java. Here we discuss the Types of Non Access Modifiersand their methods and code implementation in Java. You can also go through our other suggested articles to learn more –

  1. Layout in Java
  2. Java Compilers
  3. Merge Sort In Java
  4. Java BufferedReader

The above is the detailed content of Non Access Modifiers in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!