Commit fb20c7b
committed
feat: Add Test class using 'this' keyword to assign instance variables
WHAT the code does:
Introduces a Test class with fields x, y, and res.
Defines getData(int x, int y) to assign method parameters to instance variables using the this keyword.
Defines display() to compute the sum of x and y and print the result.
Provides a JavKeyword1 driver class with main() that creates a Test object, sets data, and displays the sum.
WHY this matters:
Demonstrates correct handling of variable shadowing in Java.
Shows how the this keyword resolves ambiguity when method parameters share names with instance variables.
Reinforces understanding of object state management across method calls.
Useful for beginners to distinguish between local scope and object fields.
HOW it works:
A Test object is instantiated in main().
getData(5,7) is called, binding parameters to the instance variables via this.x and this.y.
display() calculates res = x + y and prints the sum (12).
The this keyword ensures the instance fields are updated rather than the local method parameters.
Tips and gotchas:
If method parameters had different names, this keyword would not be required but is often kept for clarity.
Leaving out this in shadowing cases would assign values to the method parameters only, leaving object fields unchanged.
this can also be used to call constructors or pass the current object as an argument.
Use-cases:
Teaching example for scope resolution and the role of this in Java.
Foundation for object state manipulation in larger programs.
Helps explain why constructor parameters often use the same names as fields.
Short key: class-test this-keyword variable-shadowing.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 62fcbee commit fb20c7b
1 file changed
+8
-13
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | | - | |
5 | | - | |
6 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
7 | 6 | | |
8 | 7 | | |
9 | | - | |
10 | | - | |
| 8 | + | |
11 | 9 | | |
12 | 10 | | |
13 | 11 | | |
14 | 12 | | |
15 | | - | |
16 | | - | |
17 | | - | |
18 | | - | |
19 | | - | |
| 13 | + | |
| 14 | + | |
20 | 15 | | |
21 | 16 | | |
22 | 17 | | |
23 | 18 | | |
24 | | - | |
| 19 | + | |
0 commit comments