🔒 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

To view or add a comment, sign in

More articles by Kavindu Ushan

  • What is Lazy loading?

    Lazy loading is a web development optimization technique that delays the loading of non-critical elements on a webpage…

    5 Comments
  • 🚀 JavaScript Tip: Mastering Strings in JavaScript ✨

    JavaScript offers three ways to work with strings: 1️⃣ Single Quotes (' ') 2️⃣ Double Quotes (" ") 3️⃣ Template Strings…

    3 Comments
  • Migrating Swagger Configuration in Spring Boot 3.x with Java 21

    Spring Boot 3.x introduces several updates to modernize its framework, including a shift to the Jakarta namespace.

    1 Comment

Explore content categories