Encapsulation in Java (Getter & Setter)
Encapsulation in Java: Getters and Setters (With Examples)
✨ Quick Summary
In this post, you’ll learn what Encapsulation is in Java and why it is important in OOP. We will understand private variables, getters, setters, and real examples to make your code more secure and professional.
In our previous post, we learned about Java Constructors. Now let’s learn one of the most important OOP concepts: Encapsulation.
1) What is Encapsulation?
Encapsulation means:
- ✅ Wrapping data (variables) and methods into a single unit (class)
- ✅ Hiding the data using private
- ✅ Accessing the data using public getter and setter methods
Encapsulation is used to make your code:
- ✅ More secure
- ✅ More controlled
- ✅ More professional
2) Why do we use private variables?
If variables are public, anyone can change them directly:
student.age = -10; // wrong but possible if public
So we keep variables private and access them using getters and setters.
3) Encapsulation Example (Getter and Setter)
class Student {
private String name;
private int age;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
public void setAge(int a) {
if (a > 0) {
age = a;
} else {
System.out.println("Invalid Age!");
}
}
public int getAge() {
return age;
}
}
public class EncapsulationExample {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("Aishwarya");
s1.setAge(22);
System.out.println("Name: " + s1.getName());
System.out.println("Age: " + s1.getAge());
}
}
4) Real-Life Example of Encapsulation
Think about an ATM machine:
- You cannot directly access bank balance variable
- You use methods like: withdraw(), deposit(), checkBalance()
That is Encapsulation.
5) Benefits of Encapsulation
- ✅ Data hiding (security)
- ✅ Better control over data
- ✅ Code becomes flexible and maintainable
- ✅ Easy to update logic inside setter methods
Conclusion
Encapsulation is one of the most important OOP concepts in Java. It helps you write clean, secure, and professional code.
In the next post, we will learn about Inheritance in Java with examples!
One of the best encapsulation tutorial
ReplyDeleteNow you have it.
ReplyDelete