🥁Modifiers
Last updated
Last updated
Modifier | Description | Example Code |
---|---|---|
Java modifiers allow controlling access to classes, variables, methods, etc. Here are some key rules:
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:
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:
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.
private
- Access only within class 👪
default
- Access within package 📦
protected
- Access within package + subclasses outside package 👪👫
public
- Access everywhere 🌎
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
Modifier | Class | Package | Subclass | Outside |
---|---|---|---|---|
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 { }
private
Y
N
N
N
default
Y
Y
N
N
protected
Y
Y
Y
N
public
Y
Y
Y
Y