1. Access Control for Class Members
Java provides a powerful access control system to protect data and methods. Access modifiers determine which parts of a program can access a class or its members. This supports strong encapsulation, one of the core pillars of OOP.
Java Access Modifiers:
- public – accessible from anywhere
- private – accessible only within the class
- protected – accessible within same package or subclasses
- default – accessible within the same package
class Employee {
public int id = 101;
private double salary = 55000;
protected String dept = "CSE";
}
2. Accessing Private Members of a Class
Private members cannot be accessed directly outside the class. They are exposed safely using getters and setters. This is the essence of encapsulation: protecting data while providing controlled access.
class Student {
private int marks;
public void setMarks(int m) {
marks = m;
}
public int getMarks() {
return marks;
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setMarks(95);
System.out.println(s.getMarks());
}
}
Output:
95
Practice Questions – Click to Reveal Answers
1️⃣ What is the role of access modifiers in Java?
Access modifiers control visibility of class members, enabling encapsulation and secure design.
2️⃣ Why can't private members be accessed directly?
Because Java enforces data protection. Private members ensure internal data safety.
3️⃣ How do getters and setters support encapsulation?
They expose data in a controlled way, preventing unauthorized modifications.
4️⃣ What is the difference between protected and default?
Protected allows subclass access; default doesn't.
5️⃣ Write a getter for a private variable
public int getX(){ return x; }