What are the Access Modifiers in Java?
Access modifiers control the visibility and scope of classes, methods, and variables. Java provides 4 access modifiers.
1. private
class Account {
private double balance = 1000;
private void showBalance() {
System.out.println("Balance: $" + balance);
}
public void accessPrivate() {
showBalance(); // Accessible within same class
}
}
2. default (Package-Private)
package package1;
class Person {
String name = "John";
void sayHello() {
System.out.println("Hello from " + name);
}
}
3. protected
public class Parent {
protected void display() {
System.out.println("Protected method");
}
}
class Child extends Parent {
void test() {
display(); // OK - inheritance access
}
}
4. public
public class Utility {
public static int add(int a, int b) {
return a + b;
}
}
Quick Reference
| Modifier | Same Class | Same Package | Subclass | Anywhere |
|---|---|---|---|---|
| private | Yes | No | No | No |
| default | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
Learn Java access control with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
