You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Encapsulation protects the instance variables from invalid value assignments, which is achieved through public getter and setter methods by writing the validation logic.
Real World Example
In a bank, there’s a minimum balance rule — say ₹5,000.
minium balance = 5000;
And if the minimum balance is not maintained, bank will charge a monthly fine of 500.
Without encapsulation, someone could set minBalance = 0, and suddenly no one gets charged the ₹500 penalty for not maintaining balance — costing the bank millions.
classBankAccount {
intminBalance = 5000; // Rule for maintaining minm balancevoidshowMinBalance() {
System.out.println("Minimum Balance Required: ₹" + minBalance);
}
}
publicclassRunner {
publicstaticvoidmain(String[] args) {
BankAccountaccount = newBankAccount(); // object creation // creating a real accountaccount.showMinBalance(); // ₹5000// Anyone can directly change it to an invalid valueaccount.minBalance = 0; // changed the balance to 0account.showMinBalance(); // 0 → Rule broken!
}
}
How can we achieve Encapsulation?
We can achieve encapsulation - by declaring the instance variable private.
"private" means - instance variables can be accessed only inside the class. So that no one can assign illegal values to instance variables.
How can we access a private variable inside main()?
we can access private instance variables inside main - by Using public methods such as getters and setters.
Getter → Retrieves the value of a private instance variable.
Setter → Assigns a value to a private instance variable, passed as a parameter.
Can include validation logic to ensure only valid values are stored.
By using getters and setters, we achieve encapsulation.
Code showing setters() and getters()
packagecom.student.management.system.oop;
publicclassStudent {
privateStringname;
privateintage;
privateintrollNumber;
// Getter and Setter for namepublicStringgetName() {
returnname;
}
publicvoidsetName(Stringname) {
this.name = name; // this initialize the instance variabe with the value we are passing
}
// Getter and Setter for agepublicintgetAge() {
returnage;
}
publicvoidsetAge(intage) {
if (age < 21 && age >= 10) {. // Validating agethis.age = age;
} else {
System.out.println("Invalid Age for Student!!");
}
}
// Getter and Setter for rollNumberpublicintgetRollNumber() {
returnrollNumber;
}
publicvoidsetRollNumber(introllNumber) { // validating rollnumberif (rollNumber >= 1) {
this.rollNumber = rollNumber;
} else {
System.out.println("Invalid Roll Number");
}
}
Student Runener class
packagecom.student.management.system.oop;
publicclassStudentRunner {
publicstaticvoidmain(String[] args) {
// Create Student objectStudents1 = newStudent();
// Set values using setterss1.setName("John Doe");
s1.setAge(15);
s1.setRollNumber(101);
// Get and print values using gettersSystem.out.println(s1.getName());
System.out.println(s1.getAge());
System.out.println(s1.getRollNumber());
}
}
How to achieve encapsulation in java?
Declare instance variables private - It controls access to instance variables from outside the class.
Provide public getter and setter methods - It prevents invalid assignments by validating values before storing them.
How to add setetrs and getters in our code?
1. Right-click inside your class file.
2. Select SOURCE (or use the menu bar: Code → Generate).
3. Click Generate Getters and Setters.
4. Select the fields you want to generate them for.
5. Click OK — the IDE will auto-create the methods.