Java Modifiers

Java Modifiers

Modifiers are keywords that you add to definitions to change their meanings. Java has a wide variety of modifiers, which are divided into two groups:

  1. Access Modifiers: Controls the access level (visibility).
  2. Non-Access Modifiers: Do not control access level, but provide other functionality.

1. Access Modifiers

Access modifiers are used to set the accessibility of classes, interfaces, variables, methods, constructors, and data members.

For Classes:

For Attributes, Methods, and Constructors:

The table below illustrates the visibility:

Modifier Same Class Same Package Subclass World
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N

Access Modifier Example

public class MyClass {
  public String publicVar = "I am public!";
  private String privateVar = "I am private!";

public void display() { // The private variable is accessible inside the class System.out.println(privateVar); } }

// In another class... public class Main { public static void main(String[] args) { MyClass obj = new MyClass(); System.out.println(obj.publicVar); // This works // System.out.println(obj.privateVar); // This would cause an error obj.display(); // This works and prints the private variable } }


2. Non-Access Modifiers

Non-access modifiers are used to provide information about the characteristics of a class, method, or variable to the JVM.

For Classes:

For Attributes and Methods:

Static and Final Example

public class Main {
  final double PI = 3.14; // A final variable (constant)
  static int instanceCount = 0; // A static variable

public Main() { instanceCount++; // Increment the static counter for each new object }

public static void main(String[] args) { Main obj1 = new Main(); Main obj2 = new Main(); System.out.println("Instances created: " + Main.instanceCount); // Access static var on the class } }