Commit fdad0be
committed
feat: Add TypesOfProperties class with encapsulated field and getter/setter
WHAT the code does:
Defines TypesOfProperties with a private field length.
Provides:
- getLength(): returns current value of length (read property).
- setLength(double length): sets value with validation (must be positive).
Defines Main with main():
- Creates a TypesOfProperties object.
- Uses setter to assign length = 12.5.
- Uses getter to retrieve and print value.
WHY this matters:
Demonstrates encapsulation by hiding data (private field) and exposing controlled access via methods.
Shows the use of getter (read-only access) and setter (write access with validation).
Introduces validation logic in setters to prevent invalid state (e.g., negative length).
Illustrates how properties map to behaviors in OOP design.
HOW it works:
obj.setLength(12.5) assigns 12.5 to length.
obj.getLength() returns 12.5, printed as output.
If a negative value were passed, setter would reject it and print "Length must be positive!".
Tips and gotchas:
Naming conventions: in larger projects, methods might use prefixes (e.g., validateAndSetLength) for clarity, though simple getters/setters are standard.
Validation currently only prints a message; in robust applications, throwing exceptions may be more appropriate.
This example uses a single property; in more complex models, encapsulation is critical for maintaining consistency across related fields.
Use-cases:
Educational example of encapsulation and property management in Java.
Foundation for building classes with validated state.
Useful in modeling real-world entities where invalid values must be prevented.
Short key: class-typesofproperties encapsulation getter-setter validation.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 5c4d448 commit fdad0be
File tree
1 file changed
+10
-18
lines changed- Section11ObjectOrientedProgramming/src
1 file changed
+10
-18
lines changedLines changed: 10 additions & 18 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
| 1 | + | |
| 2 | + | |
4 | 3 | | |
5 | 4 | | |
6 | | - | |
7 | | - | |
| 5 | + | |
8 | 6 | | |
9 | 7 | | |
10 | 8 | | |
11 | 9 | | |
12 | | - | |
13 | | - | |
14 | | - | |
15 | | - | |
| 10 | + | |
| 11 | + | |
16 | 12 | | |
17 | 13 | | |
18 | | - | |
19 | | - | |
20 | | - | |
| 14 | + | |
21 | 15 | | |
22 | 16 | | |
23 | 17 | | |
24 | 18 | | |
25 | | - | |
26 | | - | |
27 | | - | |
28 | | - | |
29 | | - | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
30 | 22 | | |
31 | 23 | | |
32 | 24 | | |
| |||
44 | 36 | | |
45 | 37 | | |
46 | 38 | | |
47 | | - | |
| 39 | + | |
0 commit comments