Posts

Showing posts with the label encapsulation in java

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. Java OOP Encapsulation Getter / Setter 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...