Access modifiers in Java define the visibility (access level) of classes, methods, constructors, and variables. They control which parts of the program can access a specific code element.
Modifier | Within Class | Within Package | Outside Package (subclass) | Outside Package |
private | ✅ Yes | ❌ No | ❌ No | ❌ No |
(default) | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
protected | ✅ Yes | ✅ Yes | ✅ Yes | ❌ No |
public | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
Accessible only within the same class.
Not accessible even in subclasses or other classes.
class Student
{ // Private data members
private String name = "Ankit";
private int rollNo = 101;
// Private method
private void display() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
}
// A public method inside the class to internally call the private method (optional)
public void callPrivateDisplay() {
display(); // Allowed: private used within the class
}
public static void main(String[] args) {
Student s = new Student();
// These lines would cause errors because private members
are not accessible outside the class:
// System.out.println(s.name); // Error
// System.out.println(s.rollNo); // Error
// s.display(); // Error
// ✅ This works because we’re accessing private method via a public method
s.callPrivateDisplay();
}
}
public specifier
class Student {
// Public data members
public String name;
public int rollNo;
// Public method
public void display() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
}
public static void main(String[] args) {
// Creating object of Student class
Student s = new Student();
// Accessing public variables directly
s.name = "Prasanjeet";
s.rollNo = 101;
// Calling public method
s.display();
}
}
class Student {
// These fields and methods are default (no modifier)
String name;
int rollNo;
void display() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
}
public static void main(String[] args) {
// Accessing default members within the same package
Student s = new Student();
s.name = "Anjali";
s.rollNo = 105;
s.display();
}
}
Protected Specifier
The protected access modifier allows access:
- Within the same class
- Within the same package
- In subclasses, even if they are in different packages
We will discuss the protected access specifier in upcoming topic Inheritance.