Commit dc61946
committed
docs: Explain use of
WHAT the update covers:
Adds detailed explanation and examples showing why `this.itemNo = itemNo;` is required in constructors when parameter names shadow instance variables.
WHY this matters:
Clarifies the difference between local parameters and instance variables in Java.
Without `this`, assignments like `itemNo = itemNo;` only reassign the parameter to itself, leaving the instance variable uninitialized (defaulting to null or 0).
Using `this.itemNo` explicitly refers to the object’s field, ensuring correct initialization.
HOW it works:
Incorrect case:
- public Product(String itemNo) { itemNo = itemNo; }
- Creates a Product but leaves the field itemNo null.
Correct case:
- public Product(String itemNo) { this.itemNo = itemNo; }
- Properly assigns the parameter value to the instance variable.
Demonstrated with examples showing null output without `this` vs correct "A25" output with `this`.
Tips and gotchas:
`this` is only required when parameter names shadow instance variables; otherwise, it can be omitted.
Using `this` improves readability and avoids subtle bugs, especially in constructors and setters.
Overusing identical parameter and field names can cause confusion; some developers adopt naming conventions like prefixing fields (e.g., itemNo vs itemNoParam).
Use-cases:
Educational note for beginners learning constructors and `this` keyword.
Prevents common mistakes in object initialization.
Forms the basis for understanding scope resolution in OOP.
Short key: docs-this-keyword constructor-parameter-shadowing.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>this keyword for disambiguating constructor parameters1 parent ae1cc9e commit dc61946
File tree
1 file changed
+5
-7
lines changed- Section11ObjectOrientedProgramming/src
1 file changed
+5
-7
lines changedLines changed: 5 additions & 7 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
| 3 | + | |
| 4 | + | |
4 | 5 | | |
5 | 6 | | |
6 | 7 | | |
| |||
22 | 23 | | |
23 | 24 | | |
24 | 25 | | |
| 26 | + | |
25 | 27 | | |
26 | 28 | | |
27 | 29 | | |
| |||
30 | 32 | | |
31 | 33 | | |
32 | 34 | | |
33 | | - | |
34 | 35 | | |
35 | 36 | | |
36 | 37 | | |
37 | | - | |
38 | 38 | | |
39 | 39 | | |
40 | 40 | | |
41 | 41 | | |
42 | | - | |
43 | 42 | | |
44 | 43 | | |
45 | 44 | | |
| |||
72 | 71 | | |
73 | 72 | | |
74 | 73 | | |
75 | | - | |
76 | | - | |
| 74 | + | |
77 | 75 | | |
78 | | - | |
| 76 | + | |
0 commit comments