Skip to content

Commit 4959b8f

Browse files
committed
feat: We create a constructor to ensure proper initialization of instance variables, improve code clarity, avoid redundant manual assignments, and maintain data integrity when creating objects.
Signed-off-by: Somesh diwan <[email protected]>
1 parent 363c6b1 commit 4959b8f

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

Section10Methods/LocalandGlobalVariables/src/constructor is used to initialize instance variables.txt

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ Automatic Initialization When Object is Created
44

55
Instance variables belong to an object, and their values need to be assigned when the object is created.
66
The constructor ensures that every object gets proper initial values without requiring manual assignment after object creation.
7-
Encapsulation & Data Integrity
7+
8+
Encapsulation & Data Integrity:
89

910
Using a constructor enforces proper data encapsulation.
1011
It ensures that objects are always created in a valid state, preventing uninitialized or inconsistent values.
11-
Avoids Manual Assignment for Each Object
12+
13+
Avoids Manual Assignment for Each Object:
1214

1315
Without a constructor, you'd have to manually set values for each object after creating it, which is repetitive and error-prone.
1416

@@ -17,17 +19,20 @@ Instead of:
1719
Company emp1 = new Company();
1820
emp1.employeeName = "Alice";
1921
emp1.salary = 50000;
22+
2023
A constructor allows:
2124

2225
Company emp1 = new Company("Alice", 50000);
2326
making code cleaner and structured.
27+
2428
Improves Code Readability & Maintainability
2529

2630
When creating multiple objects, a constructor provides a clear and consistent way to initialize them.
2731
This improves the structure and readability of the code.
2832
Supports Different Initialization Needs (Overloading)
2933

3034
Constructors can be overloaded, allowing different initialization patterns based on different requirements.
35+
3136
Example:
3237

3338
public Company(String employeeName) {
@@ -36,4 +41,4 @@ public Company(String employeeName) {
3641

3742
Conclusion:
3843
We create a constructor to ensure proper initialization of instance variables, improve code clarity,
39-
avoid redundant manual assignments, and maintain data integrity when creating objects.
44+
avoid redundant manual assignments, and maintain data integrity when creating objects.

0 commit comments

Comments
 (0)