๐ŸฅModifiers

Modifier
Description
Example Code

Public

Accessible from any class or package

public class ExampleClass { }

Private

Accessible only within the same class

private int exampleVariable;

Protected

Accessible within the same class and its subclasses

protected void exampleMethod() { }

Static

Belongs to the class rather than a specific instance

public static void exampleMethod() { }

Final

Cannot be modified once initialized

private final int EXAMPLE_CONSTANT = 10;

Abstract

Cannot be instantiated and must be extended

public abstract class ExampleAbstractClass { }

Rules for Java Modifiers

Java modifiers allow controlling access to classes, variables, methods, etc. Here are some key rules:

Access Modifiers

  • public - Accessible from any class

  • protected - Accessible within package and subclasses

  • default (no modifier) - Accessible within the package only

  • private - Accessible only within the class

For example:

public class Main {

  private String name; //only accessible within Main
  
  void print() { //default access
    
  }

}

Non-Access Modifiers

  • static - Belongs to the class rather than an instance

  • final - Cannot be inherited or modified

  • abstract - Method signature without implementation

  • synchronized - One thread access at a time

For example:

public abstract class Parent {

  public static final int VALUE = 10;
  
  protected synchronized void print() {
    //...
  }

}

Rules

  • Only one public class per file

  • Public class must match filename

  • Interface methods are implicitly public

  • Variables are default access if no modifier

So modifiers allow flexible access control in Java.

Java Access Levels

  • private - Access only within class ๐Ÿ‘ช

  • default - Access within package ๐Ÿ“ฆ

  • protected - Access within package + subclasses outside package ๐Ÿ‘ช๐Ÿ‘ซ

  • public - Access everywhere ๐ŸŒŽ

Access Summary

Modifier
Class
Package
Subclass
Outside

private

Y

N

N

N

default

Y

Y

N

N

protected

Y

Y

Y

N

public

Y

Y

Y

Y

Key Points:

  • private is most restrictive, public is most open

  • Omitting access modifier defaults to package-level access

  • protected gives subclass access outside package

  • Understanding access modifiers is key to encapsulation

Last updated