Modifiers
Modifiers
Modifiers in Java are special keywords that are used to change the behavior, visibility, or access level of classes, methods, variables, or constructors. They help control how and where these elements can be used in a program.
Types of Access Modifiers:
- public β Accessible from anywhere
- private β Accessible only inside the same class
- protected β Accessible within the same package and child classes
- default (no keyword) β Accessible only within the same package
Β
Example
public class Main {
Β Β // public variable β can be accessed from anywhere
Β Β public int publicVar = 10;
Β Β // private variable β can be accessed only inside this class
Β Β private int privateVar = 20;
Β Β // protected variable β accessible in same package and child classes
Β Β protected int protectedVar = 30;
Β Β // default variable (no modifier) β accessible only within same package
Β Β int defaultVar = 40;
Β Β public static void main(String[] args) {
Β Β Β Β // Creating object of Main class
Β Β Β Β Main obj = new Main();
Β Β Β Β // Accessing public variable (allowed everywhere)
Β Β Β Β System.out.println("Public: " + obj.publicVar);
Β Β Β Β // Accessing private variable (allowed inside same class only)
Β Β Β Β System.out.println("Private: " + obj.privateVar);
Β Β Β Β // Accessing protected variable
Β Β Β Β System.out.println("Protected: " + obj.protectedVar);
Β Β Β Β // Accessing default variable
Β Β Β Β System.out.println("Default: " + obj.defaultVar);
Β Β }
}
Comparison Table of Access Modifiers in Java
| ModifierΒ | Within Class | Within Package | Outside Package (Subclass) | Outside Package (Non-Subclass) |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes |
| protected | Yes | Yes | Yes | No |
| Default | Yes | Yes | No | No |
| private | Yes | No | No | No |
Β