|
| 1 | +/* |
| 2 | +🧩 Definition of Encapsulation (in Java) |
| 3 | +
|
| 4 | +Encapsulation is one of the main principles of Object-Oriented Programming (OOP). |
| 5 | +It means wrapping data (variables) and methods (functions) that operate on that data into a single unit — usually a class — and restricting direct access to some of the object’s components. |
| 6 | +
|
| 7 | +In simple words: |
| 8 | +
|
| 9 | +Encapsulation is the process of binding data and code together while hiding the internal details of how the data is stored or modified. |
| 10 | +
|
| 11 | +🔒 Purpose of Encapsulation |
| 12 | +
|
| 13 | +Encapsulation’s main goals are: |
| 14 | +
|
| 15 | +Data Hiding: |
| 16 | +
|
| 17 | +The object’s internal data is not directly accessible from outside the class. |
| 18 | +
|
| 19 | +Only specific, controlled methods can access or modify it. |
| 20 | +
|
| 21 | +This prevents accidental or unauthorized changes. |
| 22 | +
|
| 23 | +Controlled Access via Getters and Setters: |
| 24 | +
|
| 25 | +To access or modify private data safely, we use getter (to read) and setter (to write) methods. |
| 26 | +
|
| 27 | +This allows us to validate or restrict values before assigning them. |
| 28 | +
|
| 29 | +🧠 How Data Hiding Works |
| 30 | +
|
| 31 | +In Java: |
| 32 | +
|
| 33 | +You make instance variables private so they cannot be accessed directly from outside the class. |
| 34 | +
|
| 35 | +You provide public methods (getters and setters) to get or set their values safely. |
| 36 | +*/ |
| 37 | +✅ Example: Encapsulation in Java |
| 38 | +class Student { |
| 39 | + // Private data (data hiding) |
| 40 | + private String name; |
| 41 | + private int age; |
| 42 | + |
| 43 | + // Getter method for 'name' |
| 44 | + public String getName() { |
| 45 | + return name; |
| 46 | + } |
| 47 | + |
| 48 | + // Setter method for 'name' |
| 49 | + public void setName(String newName) { |
| 50 | + name = newName; |
| 51 | + } |
| 52 | + |
| 53 | + // Getter method for 'age' |
| 54 | + public int getAge() { |
| 55 | + return age; |
| 56 | + } |
| 57 | + |
| 58 | + // Setter method for 'age' with validation |
| 59 | + public void setAge(int newAge) { |
| 60 | + if (newAge > 0) { |
| 61 | + age = newAge; |
| 62 | + } else { |
| 63 | + System.out.println("Age must be positive!"); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +public class Main { |
| 69 | + public static void main(String[] args) { |
| 70 | + Student s = new Student(); |
| 71 | + |
| 72 | + // Accessing private data using setter methods |
| 73 | + s.setName("Alice"); |
| 74 | + s.setAge(20); |
| 75 | + |
| 76 | + // Getting private data using getter methods |
| 77 | + System.out.println("Name: " + s.getName()); |
| 78 | + System.out.println("Age: " + s.getAge()); |
| 79 | + |
| 80 | + // Trying to set invalid age |
| 81 | + s.setAge(-5); |
| 82 | + } |
| 83 | +} |
0 commit comments