๐ฅModifiers
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 classprotected
- Accessible within package and subclassesdefault
(no modifier) - Accessible within the package onlyprivate
- Accessible only within the class
For example:
Non-Access Modifiers
static
- Belongs to the class rather than an instancefinal
- Cannot be inherited or modifiedabstract
- Method signature without implementationsynchronized
- One thread access at a time
For example:
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
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 openOmitting access modifier defaults to package-level access
protected
gives subclass access outside packageUnderstanding access modifiers is key to encapsulation
Last updated