🔒 Why Encapsulation Matters in Java
When I started learning Java, I wondered: "Why do we need getters and setters? Why not just make fields public and access them directly?"
Then I built this simple Student class, and it clicked. 💡
public class Student{
private int id;
private String firstName;
private String lastName;
private int age;
public Student(int id, String fName, String lName, int age){
this.id = id;
this.firstName = fName;
this.lastName = lName;
this.age = age;
}
public int getId() {
return id;
}
public void setFirstName(String fName){
if(fName != null && !fName.trim().isEmpty()){
this.firstName = fName;
}
}
public void setLastName(String lName) {
if (lName != null && !lName.trim().isEmpty()) {
this.lastName = lName;
}
}
public String getName(){
return this.firstName + " " + this.lastName;
}
public void setAge(int age) {
if (age < 0 || age > 150) {
System.out.println("Invalid age");
return;
}
this.age = age;
}
public int getAge(){
return age;
}
}
class Main{
public static void main(String args[]){
Student newStd = new Student(001, "Kavindu", "Ushan", 28);
System.out.println("======== Student Details ========");
System.out.println("Student Id: " + newStd.getId());
System.out.println("Student Name: "+ newStd.getName());
System.out.println("Student Age: "+ newStd.getAge());
System.out.println("=================================");
System.out.println();
System.out.println("====== After Set Student Age ======");
newStd.setAge(-25);
System.out.println("Student Name: " + newStd.getName());
System.out.println("Student Age: " + newStd.getAge());
System.out.println("=================================");
}
}
Console output :
======== Student Details ========
Student Id: 1
Student Name: Kavindu Ushan
Student Age: 28
=================================
====== After Set Student Age ======
Invalid age
Student Name: Kavindu Ushan
Student Age: 28
=================================
The Problem: If fields are public, anyone can set invalid data:
newStd.age = -25; // Nothing stops this!
newStd.firstName = ""; // Empty name? Sure!
The Solution: Encapsulation By making fields private and using getters/setters, I can:
✅ Validate data before accepting it
✅ Protect my object from invalid states
✅ Control how data is accessed and modified
Real Example from My Code:
When I tried to set age to -25, my setter caught it:
newStd.setAge(-25);
// Output: "Invalid age"
// Age remains 28 (unchanged)
The validation in my setAge() method prevented bad data from corrupting my Student object!
Another Win: My getName() method combines firstName and lastName:
return this.firstName + " " + this.lastName;
Later, if I change how names are stored internally, external code doesn't break. That's the power of encapsulation!
Encapsulation isn't about making code complicated—it's about making it robust, maintainable, and safe.
For fellow Java beginners: Start practicing encapsulation now. Your future self (and your team) will thank you! 🚀
~ Kavindu Ushan