Skip to content

Commit 05254de

Browse files
committed
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]>
1 parent ec9f2b7 commit 05254de

File tree

1 file changed

+48
-35
lines changed

1 file changed

+48
-35
lines changed
Lines changed: 48 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,3 @@
1-
/*
2-
Getter and Setter Methods in Java
3-
4-
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
241
class Person2 {
252
private String name; // Private variable
263
private int age; // Private variable
@@ -43,15 +20,14 @@ public int getAge() {
4320
// Setter method for age with validation
4421
public void setAge(int age) {
4522
if (age > 0) {
46-
// Ensuring valid age
23+
// Ensuring valid age.
4724
this.age = age;
4825
} else {
4926
System.out.println("Age must be positive.");
5027
}
5128
}
5229
}
5330

54-
// Main class: To run the application
5531
public class GetAndSet {
5632
public static void main(String[] args) {
5733
Person2 p = new Person2();
@@ -61,27 +37,64 @@ public static void main(String[] args) {
6137
p.setAge(25);
6238

6339
// Using getter methods
64-
System.out.println("Name: " + p.getName()); // Output: Name: John Doe
65-
System.out.println("Age: " + p.getAge()); // Output: Age: 25
40+
System.out.println("Name: " + p.getName());
41+
System.out.println("Age: " + p.getAge());
6642

6743
// Attempting to set invalid age
68-
p.setAge(-5); // Output: Age must be positive.
44+
p.setAge(-5);
6945
}
7046
}
7147

7248
/*
49+
Getter and Setter Methods in Java:
50+
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+
7372
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.
7885
7986
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:
8192
Class Structure: Person2 is now a top-level class, making it clearer and ensuring proper structure for the program.
8293
Usage of Main class: The Main class is now separate and contains the main() method to run the code.
8394
What You Can Do with Getters and Setters:
8495
Validation: Ensure that data entered is valid (like with setAge()).
8596
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.
100+
*/

0 commit comments

Comments
 (0)