You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feat: Add GetAndSet class demonstrating encapsulation with getters and setters
WHAT the code does:
- Defines `Person2` class with **private fields**:
- `name` (String)
- `age` (int)
- Provides public getter and setter methods:
- `getName()` / `setName(String name)`
- `getAge()` / `setAge(int age)` with validation (`age > 0`).
- Defines `GetAndSet` class with `main()`:
- Creates a `Person2` object.
- Sets valid values (`"John Doe"`, `25`) using setters.
- Prints values using getters.
- Attempts to set invalid age (`-5`) → prints validation message.
WHY this matters:
- Demonstrates **encapsulation**, a core OOP principle.
- Shows how getters and setters control access to private fields.
- Illustrates **data validation** in setters to ensure object integrity.
HOW it works:
1. `p.setName("John Doe")` → assigns name.
2. `p.setAge(25)` → valid, assigns age.
3. `getName()` and `getAge()` print values.
4. `p.setAge(-5)` → fails validation, prints `"Age must be positive."`.
Tips & gotchas:
- Always keep fields private to enforce controlled access.
- Setter validations prevent invalid state in objects.
- Getter/setter names follow JavaBean conventions, useful for frameworks (e.g., Spring).
- Can extend validation (e.g., `maxAge` limit, null/empty name check).
Use-cases:
- Educational example for **encapsulation and access control**.
- Basis for modeling domain entities with controlled state.
- Prepares for frameworks relying on JavaBean properties.
- Helps enforce business rules at the object level.
Short key: class-get and set-encapsulation-validation.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>
In Java, getter and setter methods are used to access and modify private fields of a class.
5
-
They are part of the encapsulation principle in Object-Oriented Programming (OOP), ensuring that the internal representation of a class is hidden from outside access
6
-
7
-
8
-
1. Why Use Getters and Setters?
9
-
Encapsulation & Data Hiding
10
-
Encapsulation helps in restricting direct access to class fields.
11
-
Fields are typically marked as private, preventing external modification.
12
-
Getters allow controlled read access, and setters provide controlled write access.
13
-
Data Validation
14
-
Setters can include validation logic to prevent invalid data from being set.
15
-
Read-Only or Write-Only Access
16
-
A class may provide a getter without a setter (making it read-only).
17
-
A class may provide a setter without a getter (making it write-only).
18
-
Logging & Debugging
19
-
You can log every time a field is accessed or modified.
20
-
Helps in tracking changes to data.
21
-
*/
22
-
23
-
// Person2 class: Represents an individual with name and age
24
1
classPerson2 {
25
2
privateStringname; // Private variable
26
3
privateintage; // Private variable
@@ -43,15 +20,14 @@ public int getAge() {
43
20
// Setter method for age with validation
44
21
publicvoidsetAge(intage) {
45
22
if (age > 0) {
46
-
// Ensuring valid age
23
+
// Ensuring valid age.
47
24
this.age = age;
48
25
} else {
49
26
System.out.println("Age must be positive.");
50
27
}
51
28
}
52
29
}
53
30
54
-
// Main class: To run the application
55
31
publicclassGetAndSet {
56
32
publicstaticvoidmain(String[] args) {
57
33
Person2p = newPerson2();
@@ -61,27 +37,64 @@ public static void main(String[] args) {
61
37
p.setAge(25);
62
38
63
39
// Using getter methods
64
-
System.out.println("Name: " + p.getName());// Output: Name: John Doe
In Java, getter and setter methods are used to access and modify private fields of a class.
51
+
They are part of the encapsulation principle in Object-Oriented Programming (OOP),
52
+
ensuring that the internal representation of a class is hidden from outside access.
53
+
54
+
1. Why Use Getters and Setters?
55
+
Encapsulation & Data Hiding.
56
+
Encapsulation helps in restricting direct access to class fields.
57
+
Fields are typically marked as private, preventing external modification.
58
+
Getters allow controlled read access, and setters provide controlled write access.
59
+
60
+
Data Validation:
61
+
62
+
Setters can include validation logic to prevent invalid data from being set,
63
+
Read-Only or Write-Only Access.
64
+
65
+
A class may provide a getter without a setter (making it read-only).
66
+
A class may provide a setter without a getter (making it write-only).
67
+
68
+
Logging & Debugging:
69
+
You can log every time a field is accessed or modified.
70
+
Helps in tracking changes to data.
71
+
73
72
Key Points:
74
-
Encapsulation: The name and age fields are private, meaning they cannot be accessed directly outside of the Person2 class. The getter and setter methods provide controlled access.
75
-
Data Validation: The setAge() method includes a validation check to ensure the age is positive before it’s set. This prevents invalid data from being assigned to the age field.
76
-
Read-Write and Write-Only Access: In this example, the name field has both a getter and a setter, allowing both read and write access. The age field also provides both getter and setter methods, with the setter including validation to ensure the data is appropriate.
77
-
Logging and Debugging: Although you haven't explicitly added logging, this pattern allows for logging in setter methods. For instance, you could log whenever the setName() or setAge() methods are called.
73
+
Encapsulation: The name and age fields are private, meaning they cannot be accessed directly outside the Person2 class.
74
+
The getter and setter methods provide controlled access.
75
+
76
+
Data Validation: The setAge() method includes a validation check to ensure the age is positive before it’s set.
77
+
This prevents invalid data from being assigned to the age field.
78
+
79
+
Read-Write and Write-Only Access: In this example, the name field has both a getter and a setter,
80
+
allowing both read and write access.
81
+
The age field also provides both getter and setter methods, with the setter including validation to ensure the data is appropriate.
82
+
83
+
Logging and Debugging: Although you haven't explicitly added logging, this pattern allows for logging in setter methods.
84
+
For instance, you could log whenever the setName() or setAge() methods are called.
78
85
79
86
Fixing the Code:
80
-
There’s a small issue with the code structure: the Person2 class is inside the GetAndSet class. It would be better to move it outside the GetAndSet class to ensure that it works as expected. Additionally, Main should be outside GetAndSet. Explanation of Changes:
87
+
There’s a small issue with the code structure: the Person2 class is inside the GetAndSet class.
88
+
It would be better to move it outside the GetAndSet class to ensure that it works as expected.
89
+
Additionally, Main should be outside GetAndSet.
90
+
91
+
Explanation of Changes:
81
92
Class Structure: Person2 is now a top-level class, making it clearer and ensuring proper structure for the program.
82
93
Usage of Main class: The Main class is now separate and contains the main() method to run the code.
83
94
What You Can Do with Getters and Setters:
84
95
Validation: Ensure that data entered is valid (like with setAge()).
85
96
Logging: Track changes to an object’s state for debugging or auditing purposes.
86
-
Control Access: You can provide read-only properties by omitting the setter, or write-only properties by omitting the getter, depending on your needs.
87
-
*/
97
+
98
+
Control Access: You can provide read-only properties by omitting the setter, or
99
+
write-only properties by omitting the getter, depending on your needs.
0 commit comments