Java Modifiers

Modifiers in Java are keywords that are used to define the scope, behavior, and accessibility of classes, variables, methods, and other elements in a Java program. Here's an overview of commonly used modifiers:

Access Modifiers:

  • Control the accessibility of classes, variables, and methods.
  • Four types: public, protected, default (no modifier), and private.
  • Example:
public class MyClass {
    private int x;
    protected void display() {
        System.out.println("Hello");
    }
}

Non-Access Modifiers:

  • Define additional properties and behavior of classes, variables, and methods.
  • Includes static, final, abstract, synchronized, transient, and volatile.
  • Example:
public class MyClass {
    static int count;
    final double PI = 3.14;
    abstract void draw();
}

Static Modifier:

  • Used to declare variables and methods as class-level instead of instance-level.
  • Static variables are shared among all instances of a class.
  • Example:
class Counter {
    static int count = 0;
    Counter() {
        count++;
    }
}

Final Modifier:

  • Indicates that a variable, method, or class cannot be modified or overridden.
  • Final variables cannot be reassigned once initialized.
  • Example:
final int MAX_VALUE = 100;

Abstract Modifier:

  • Used to declare abstract classes and methods.
  • Abstract classes cannot be instantiated, and abstract methods must be implemented by subclasses.
  • Example:
abstract class Shape {
    abstract void draw();
}

 

Summary

Modifiers provide control over the accessibility, behavior, and properties of elements in a Java program, allowing for better organization, encapsulation, and reusability of code. Understanding how to use modifiers effectively is essential for writing efficient and maintainable Java applications.