Java Program - Encapsulation (Private Members)¶
Concept Explanation¶
What is it?¶
Encapsulation is one of the four fundamental OOP concepts. It involves bundling the data (variables) and the methods that act on the data into a single unit (class) and restricting direct access to some of an object's components.
Why is it important?¶
It protects data from accidental corruption. By making fields private and providing public methods to access them, you can control how fields are accessed or modified (e.g., preventing a negative age).
Implementations¶
class Student {
// Private variables (Data Hiding)
private int id;
private String name;
// Public Getter for ID
public int getId() {
return id;
}
// Public Setter for ID with Validation
public void setId(int id) {
if (id > 0) {
this.id = id;
} else {
System.out.println("Error: Invalid ID. Must be positive.");
}
}
// Public Getter for Name
public String getName() {
return name;
}
// Public Setter for Name
public void setName(String name) {
this.name = name;
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
Student s1 = new Student();
// s1.id = 101; // Compile Error: id has private access
s1.setId(101);
s1.setName("Alice");
System.out.println("Student ID: " + s1.getId());
System.out.println("Student Name: " + s1.getName());
// Test Validation
s1.setId(-5); // Will print error message
}
}
Explanation¶
- Private Fields:
idandnamecannot be accessed directly by other classes. - Public Methods:
getId()andsetId()provide a controlled interface. - Logic in Setters: The
setIdmethod checks if the input is valid before assignment. This logic would be impossible with direct public field access.
Related Concepts¶
"Encapsulation is the first step towards a robust and secure design." - Anonymous