Java Non-Access Modifiers

πŸ”Ή Java Non-Access Modifiers

Non-access modifiers in Java provide additional properties or behavior to classes, methods, and variables. They do not control access but affect functionality, memory allocation, or inheritance.


βœ… 1. final Modifier

  • Variable β†’ Value cannot be changed after initialization.

  • Method β†’ Cannot be overridden in subclass.

  • Class β†’ Cannot be inherited.

// final variable
class Circle {
final double PI = 3.14159;
}

// final method
class Parent {
final void show() {
System.out.println("Parent method");
}
}

// final class
final class MathUtils {
static int add(int a, int b) { return a + b; }
}


βœ… 2. static Modifier

  • Belongs to class rather than object.

  • Shared among all objects.

  • Can be used with variables, methods, blocks, and nested classes.

class Counter {
static int count = 0;

Counter() { count++; }
}

public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println("Count = " + Counter.count); // shared across objects
}
}


βœ… 3. abstract Modifier

  • Abstract class β†’ Cannot create objects, can have abstract methods.

  • Abstract method β†’ Declared without body, must be implemented in subclass.

abstract class Shape {
abstract void draw();
}

class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}


βœ… 4. synchronized Modifier

  • Used in multithreading to make a method thread-safe.

  • Ensures only one thread executes the method at a time.

class Counter {
int count = 0;

synchronized void increment() {
count++;
}
}


βœ… 5. volatile Modifier

  • Ensures the variable is always read from main memory in multithreaded programs.

  • Useful for shared variables.

class Shared {
volatile boolean flag = true;
}

βœ… 6. transient Modifier

  • Prevents serialization of a variable.

  • Useful when you don’t want sensitive data to be saved.

class User implements java.io.Serializable {
String name;
transient String password; // won't be serialized
}

βœ… 7. native Modifier

  • Declares that a method is implemented in native code (C/C++), not Java.

class Example {
native void display(); // implemented in C
}

βœ… Key Points

Modifier Used For
final Constant variables, prevent method overriding, prevent class inheritance
static Shared class members, called without object
abstract Abstract classes/methods, for incomplete class behavior
synchronized Thread safety for methods
volatile Shared variable consistency across threads
transient Skip serialization of variables
native Call methods implemented in other languages (C/C++)

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

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