🥁Modifiers
Modifier | Description | Example Code |
---|---|---|
Public | Accessible from any class or package |
|
Private | Accessible only within the same class |
|
Protected | Accessible within the same class and its subclasses |
|
Static | Belongs to the class rather than a specific instance |
|
Final | Cannot be modified once initialized |
|
Abstract | Cannot be instantiated and must be extended |
|
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
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 openOmitting access modifier defaults to package-level access
protected
gives subclass access outside packageUnderstanding access modifiers is key to encapsulation
Last updated